自动部署shell(结合Jenkins)
#!/bin/bash
NAME=(`ps -ef|grep tomcat|egrep -v '(grep|/bin/sh|\<tail)'|sed -r 's/^.*-Dcatalina.base=(.*)$/\1/'|awk '{print $1}'`)
NUM=`echo ${#NAME[*]}`
BACKUPPATH="/www/backup"
DIR="/www/target"
TIME=$(date +%Y%m%d%H%M)
TOMLIST=($(ls /opt/tomcat7* -d))
#无论是单个或者多个tomcat都要进行身份鉴别,鉴别标准就是你输入的项目名。tomcat没启则s=1反之则killtomcat进程
#######################################################
s=0
if [ $NUM -eq 0 ];then
echo "没有找到存活的TOMCAT."
exit 1
else
for i in ${NAME[*]};do
if grep "${1}\"" $i/conf/server.xml &> /dev/null;then #根据用户传的参数(工程名)在tomcat配置文件中搜索
s=0
NAME=$i
PID=`ps -ef|grep tomcat |grep $NAME/conf| grep -v "grep" | awk '{print $2}'`
echo "关闭tomcat服务,tomcat id is:$PID"
kill -9 $PID
echo "tomcat服务已停止!!!"
break
else
s=1
fi
done
fi
#tomcat没启就走这里(s=1),查找你选择的代码所在的TOMCAT是不是存在的,如果存在就将s设置为0(找到需要的tomcat路径)
if [ $s -eq 1 ];then
for i in ${TOMLIST[*]};do
if grep "${1}\"" $i/conf/server.xml &> /dev/null;then
s=0
NAME=$i
echo "正在启动匹配到的tomcat."
nohup $i/bin/startup.sh &
break
else
continue
fi
done
fi
#如果tomcat不存在则退出脚本
if [ $s -eq 1 ];then
echo "脚本没法找到TOMCAT."
exit 2
fi
#备份
cd $DIR
echo "备份工程"
tar -zcf $BACKUPPATH/$1$TIME.tar.gz $1
#删除原来的工程文件
rm -rf $1
#将Jenkins的传过来的包放到tomcat容器下(Jenkins传来的包设置放到/root下面的)
mv /root/$1 $DIR
STARTPATH="$NAME/bin"
echo "准备启动tomcat服务!!,startpath is:$STARTPATH"
cd $STARTPATH
./startup.sh
NEW_PID=`ps -ef|grep tomcat |grep $NAME/conf | grep -v "grep" | awk '{print $2}'`
if [ "$NEW_PID" == "" ]
then
echo "启动失败!!"
else
echo "启动成功,tomcat new id is:$NEW_PID"
fi