您的位置:首页 > 编程语言 > Python开发

Android自动打包,加固/上传蒲公英/修改数据库等Python版

2018-03-08 13:49 537 查看
# -*- coding:utf-8 -*-
# !/usr/bin/env python3
# name : alenx
#
# pip3 install paramiko, pymysql
#
from datetime import datetime
import fnmatch, os, paramiko, pymysql, requests

# ------------------------------------------------------------------------------------------------------------
# 账户信息
# branch
branch = 'cz1.0.5'

# 自己的静态服务器账号
hosts = "10.10.0.11"
username = "admin"
passwd = "Demo2088@@"

# 360加固账号
user = 'demo'
pawd = 'Demo2088@@'

# build mode
confDebug = "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 URL
TestURL = "https://static.test.com/android_app/demotest-release.apk"
ProURL = "https://static.test.com/android_app/demo-release.apk"
# 蒲公英Key
PGY_key = "9c86dd6fb80a0dc8286d7xxxxx841d91"
# 蒲公英APIKey
PGY_APIkey = "220fd5e840f4756axxxxxxbdb80e2e80"
# 蒲公英URL
PGY_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,
4000
"demo.jks")
keystore_alias = "financeyun"
keystore_pass = "demo123456"
key_pass = "demo123456"
app_path = os.path.join(APK_PATH, '*-demo.apk')

# ------------------------------------------------------------------------------------------------------------
# SQL
INSTER = "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 project
def 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  Project
def 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")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐