mac电脑
安装homebrew(已安装请跳过)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
安装sshpass
- 下载源代码,前往 sshpass 的官方网站,下载适合您系统的最新稳定版本的源代码包。
- 解压缩文件: 将下载的文件解压缩到您选择的位置。
- 在解压后的文件夹中打开终端,执行以下命令:
./configure
make
sudo make install
这将会编译并安装 sshpass 到您的系统中。
安装rsync同步工具
brew install rsync
配置服务器免密
生成公/私钥(生成过的请跳过)
ssh-keygen -t rsa -b 4096 -C "zhuangyan@163.com"
执行公钥拷贝,命令执行后需要输入服务器密码
ssh-copy-id -i /Users/zhuangyan/.ssh/deploy_zy_rsa.pub username@remoteserver
验证免密是否成功
ssh -i /Users/zhuangyan/.ssh/deploy_zy_rsa username@remoteserver
maven打包配置
<!-- 其他插件配置 -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>run-local-script</id>
<phase>package</phase> <!-- 执行阶段,例如这里设置为 package -->
<goals>
<goal>exec</goal>
</goals>
<configuration>
<!-- 设置您的本地脚本路径 -->
<executable>/Users/zhuangyan/project/java/myTest/zzyDeploy/pom_package_deploy_and_restart.sh</executable>
<!-- 传递属性值作为参数 -->
<arguments>
<argument>false</argument>
<argument>10.10.10.104</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
同步脚本pom_package_deploy_and_restart.sh
#!/bin/bash
isExe=$1
server_ip=$2
rsa_file=/Users/zhuangyan/.ssh/deploy_zy_rsa
server_user=test
server_pwd=Centos7_templete
deploy_from_file_one=/Users/zhuangyan/project/java/myTest/target/mytest/classes/
deploy_from_file_two=/Users/zhuangyan/project/java/myTest/target/mytest/lib/
deploy_to_file_one=/home/test/myTest/classes
deploy_to_file_two=/home/test/myTest/lib
echo "-----------------编译完成-----------------"
if [ "$isExe" = "true" ]; then
ssh -i ${rsa_file} -o BatchMode=yes ${server_user}@${server_ip} 'echo -n' 2>/dev/null
if [ $? -eq 0 ]; then
echo "-----------------可以免密-----------------"
else
echo "-----------------配置免密-----------------"
sshpass -p ${server_pwd} ssh-copy-id -i ${rsa_file} ${server_user}@${server_ip}
echo "-----------------配置完成-----------------"
fi
echo "----------------安装包解压----------------"
mkdir target/mytest/
tar -xf target/myTest-dist.tar.gz -C target/mytest/
echo "-----------------开始同步-----------------"
rsync -avz -e "ssh -i ${rsa_file}" ${deploy_from_file_one} ${server_user}@${server_ip}:${deploy_to_file_one}
rsync -avz -e "ssh -i ${rsa_file}" ${deploy_from_file_two} ${server_user}@${server_ip}:${deploy_to_file_two}
echo "-----------------同步完成-----------------"
echo "-----------------重启服务-----------------"
ssh -i ${rsa_file} test@${server_ip} '/home/test/myTest/restart.sh restart'
echo "-----------------重启完成-----------------"
else
echo "-----------------跳过部署-----------------"
fi