[转] 快速部署Tomcat项目的Shell脚本

服务器

浏览数:183

2019-8-16

  为了做集群测试,在每台机器上装了3个tomcat,每次发布项目的时候都要反复敲一些命令,重启tomcat之前先检查tomcat进程有没有停掉,没有还要手动kill该进程。

  发布次数多了,操作就比较繁琐了,索性写个脚本一键发布,省时省力^_^。

  把deploy.sh和restart.sh分别拷贝到3个tomcat的bin目录下,再用chmod +x给这两个脚本赋上可执行权限。

  一键发布命令:./deploy.sh 项目war包    例如:./deploy.sh /home/test.war

  说明:deploy.sh会先清空tomcat下的ROOT目录,再将指定的war包加压至ROOT目录,最后执行restart.sh重启tomcat。

  代码如下:

#!/bin/sh

war=$1
bin=$(cd `dirname $0`; pwd)

if [ ! -n "${war}" ]; then
    echo "***Usage: $0 [project.war]"
    exit 0
fi
if [ ! -f "${war}" ]; then
    echo "***Error: ${war} does not exist."
    exit 0
fi
if [ ! "${war##*.}" = "war" ]; then
    echo "***Error: ${war} is not a war file."
    exit 0
fi

echo "Deploy ${war##*/}..."
rm -rf ${bin}/../webapps/ROOT/ && unzip -qo ${war} -d ${bin}/../webapps/ROOT/
rm -rf ${bin}/../work/Catalina/localhost/
echo "Restart tomcat..."
exec ${bin}/restart.sh

 说明:restart.sh是用来重启tomcat的,如果tomcat没有启动则直接启动,如果已经启动就先shutdown再启动,如果shutdown之后3s没有停掉tomcat进程,则kill掉原来的进程再启动。 

 如需重启tomcat则使用命令:./restart.sh 或 ./restart.sh -v (参数-v表示启动时打印tomcat启动日志)

 代码如下:

#!/bin/sh

bin=$(cd `dirname $0`; pwd)
pid=$(ps aux | grep tomcat | grep -v grep | grep -v restart | grep ${bin} | awk '{print $2}') 

if [ -n "${pid}" ]; then
    echo "Shutdown..."
    sh ${bin}/shutdown.sh
    sleep 3

    pid=$(ps aux | grep tomcat | grep -v grep | grep -v restart | grep ${bin} | awk '{print $2}')
    if [ -n "${pid}" ]; then
        kill -9 ${pid}
        sleep 1
    fi
fi

echo "Startup..."
sh ${bin}/startup.sh
if [ "$1" = "-v" ]; then
    tail -f -n 600 ${bin}/../logs/catalina.out
fi

 如果Tomcat 配置了日志切割的话:

#!/bin/sh

bin=$(cd `dirname $0`; pwd)
pid=$(ps aux | grep tomcat | grep -v grep | grep -v restart | grep ${bin} | awk '{print $2}') 


if [ -n "${pid}" ]; then
    echo "Shutdown..."
    sh ${bin}/shutdown.sh
    sleep 3

    pid=$(ps aux | grep tomcat | grep -v grep | grep -v restart | grep ${bin} | awk '{print $2}')
    if [ -n "${pid}" ]; then
        kill -9 ${pid}
        sleep 1
    fi
fi

echo "Startup..."
sh ${bin}/startup.sh
if [ "$1" = "-v" ]; then
    tail -f -n 600 ${bin}/../logs/$(date +%Y-%m-%d).catalina.out
fi

原文链接:https://www.linuxidc.com/Linux/2016-01/127258.htm

作者:JMCui