每次更新jar包手动上传就非常的麻烦就写了一个maven自动打包上传服务器并运行的脚本来解放双手来摸鱼
需要安装的工具 expect
CentOS: yum install expect
Mac: brew insatll expect
配置mvn路径 略
编写本地脚本
#!/bin/sh
echo " >>> mvn开始打包 ..."
jarpath_orig=`mvn clean package |grep 'Building jar:' `
jarpath=${jarpath_orig#*:}
jarfile=${jarpath##*/}
host="192.168.199.666"
username="root"
password="1"
upload_floder="/opt/java/[你项目的目录]/upload/"
program="/opt/java/[你项目的目录]/"
echo " >>> 打包完成 >$jarfile< 准备上传至服务器目录:$upload_floder "
expect -c "
set timeout -1
spawn scp -r $jarpath $username@$host:$upload_floder$jarfile
expect {
yes/no { send \"yes\r\"; exp_continue }
*assword* { send \"$password\r\" }
};
expect 100%
expect eof ;
"
echo " jar 包上传完成 ..."
expect -c "
set timeout 30
spawn ssh $username@$host
expect *assword* { send \"$password\r\" }
expect #
send \"cd $program && ./start.sh stop&&rm -f *.jar \r\"
send \"cd $upload_floder && /bin/cp *.jar ../filder/anzhuang.jar && mv *.jar ../ \r\"
send \"cd $program && ./start.sh \r\"
interact # 等待用户输入
expect eof ; # 等待命令执行完后切换到原用户
"
服务器脚本
#!/bin/bash
#这里可替换为你自己的执行程序
APP_NAME=*.jar
logname=`date +%Y%m%d_%H%M%S`"_start.log"
#使用说明,用来提示输入参数
usage() {
echo "Usage: sh 执行脚本.sh [start|stop|restart|status]"
start
exit 1
}
#检查程序是否在运行
is_exist(){
pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}' `
#如果不存在返回1,存在返回0
if [ -z "${pid}" ]; then
return 1
else
return 0
fi
}
#启动方法
start(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is already running. pid=${pid} ."
else
nohup java -jar $APP_NAME > ./log/$logname 2>&1 &
tail -f ./log/$logname
fi
}
#停止方法
stop(){
is_exist
if [ $? -eq "0" ]; then
kill -9 $pid
echo "${APP_NAME} is killd"
else
echo "${APP_NAME} is not running"
fi
}
#输出运行状态
status(){
is_exist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is running. Pid is ${pid}"
else
echo "${APP_NAME} is NOT running."
fi
}
#重启
restart(){
stop
start
}
#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
"start")
start
;;
"stop")
stop
;;
"status")
status
;;
"restart")
restart
;;
*)
usage # 自动执行
;;
esac
最后
整个逻辑非常的简单 mvn 打包 -> 拿到jar包路径 -> 上传至服务器某个目录 -> 执行启动命令 -> 完成
大体的逻辑就是这样的,如果是部署微服务啥的就是再复杂些。
刚接触shell脚本感觉某些造作要比Java方便的多~
标题:每次更新jar包手动上传就非常的麻烦就写了一个maven自动打包上传服务器并运行的脚本来解放双手来摸鱼
作者:llilei
地址:http://solo.llilei.work/articles/2021/02/20/1613810797828.html