需要本地打包Java Maven项目,将 jar 上传至服务器,并执行指定 shell 脚本。
解析带有命名空间的 XML 比较繁琐,自带的ElementTree
解析中没有办法比较方便的获取命名空间的信息。
使用iterparse()
函数的话可以获取更多关于命名空间处理范围的信息。
如果要处理的 XML 文本除了要使用到其他高级 XML 特性外,还要使用到命名空间,建议最好是使用lxml
函数库来代替ElementTree
。
# -*- coding: utf-8 -*-
import os
import sys
from datetime import datetime
import paramiko
from xml.etree.ElementTree import parse
# remote config
hostname = ''
ssh_port = 22
username = ''
password = ''
remote_jar_dir = ''
remote_bash_dir = ''
execute_bash = ''
# local config
project_path = r''
pom_path = project_path + os.sep + 'pom.xml'
target_path = project_path + os.sep + 'target'
# other
rate_set = set()
def mvn_clean_install():
print('project path:', project_path)
os.chdir(project_path)
if not os.path.exists(pom_path):
raise FileNotFoundError('Wrong path, pom.xml does not exist.')
print('package begin... ', datetime.now())
os.system('mvn clean install')
print('package end... ', datetime.now())
if not os.path.exists(target_path):
raise FileNotFoundError('Package failed, target path does not exist.')
os.chdir(project_path)
mvn_jar_name = parse_pom()
mvn_jar_path = target_path + os.sep + mvn_jar_name
if not os.path.exists(mvn_jar_path):
raise FileNotFoundError(f'No [{mvn_jar_name}] found at the path [{target_path}].')
return mvn_jar_path, mvn_jar_name
def parse_pom():
pom = parse(pom_path)
artifactId = pom.find('{http://maven.apache.org/POM/4.0.0}artifactId').text
version = pom.find('{http://maven.apache.org/POM/4.0.0}version').text
return f'{artifactId}-{version}.jar'
def upload(_jar_path, _jar_name):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, ssh_port, username=username, password=password)
remote_path = remote_jar_dir + _jar_name
print('remote path:', remote_path)
client.exec_command('sudo rm -rf ' + remote_path)
transport = client.get_transport()
sftpClient = paramiko.SFTPClient.from_transport(transport)
print('upload begin... ', datetime.now())
sftpClient.put(_jar_path, remote_path, put_call_back)
print('upload end... ', datetime.now())
if execute_bash:
client.exec_command(f'cd {remote_bash_dir}; sh {execute_bash}')
client.close()
def put_call_back(start, end):
process = (float(start) / end) * 100
rate = int(process)
if rate not in rate_set:
rate_set.add(rate)
print('upload progress: |' + '█' * rate + ' ' * (100 - rate) + '|', '%.2f%%' % process)
if __name__ == '__main__':
if len(sys.argv) > 2:
project_path = sys.argv[1]
execute_bash = sys.argv[2]
jar_path, jar_name = mvn_clean_install()
upload(jar_path, jar_name)