为了方便管理tomcat,比如查看tomcat进程、启动、关闭杀进程、重启、看日志,写了个脚本。
#!/bin/bash
us=boss
tomcat_dir="/home/boss/inv_server0"
if [ -d ${tomcat_dir} ]; then
cd ${tomcat_dir}
else
echo "cannot find serverdir...exit"
exit 0
fi
sv=${tomcat_dir##*/}
m_date=$(date +%Y%m%d_%H%M)
start_sh=${tomcat_dir}"/bin/startup.sh"
stop_sh=${tomcat_dir}"/bin/shutdown.sh"
log=${tomcat_dir}"/logs/catalina.out"
function log_tm {
if [ -f ${log} ]; then
tail -500f $log
else
echo "cannot find log"
fi
}
function start_tm {
if [ $(ps -ef | grep java | grep ${us} | grep ${sv}/bin | grep -v grep | wc -l) -eq '0' ]; then
nohup $start_sh >/dev/null 2>&1 &
else
echo "The tomcat is already started!"
exit 0
fi
sleep 1
log_tm
}
function stop_tm {
if [ $(ps -ef | grep java | grep ${sv}/bin | grep ${us} | grep -v grep | wc -l) -eq '1' ]; then
$stop_sh
else
echo "The tomcat is not running!"
exit 0
fi
sleep 2
if [ $(ps -ef | grep java | grep ${sv}/bin | grep ${us} | grep -v grep | wc -l) -eq '0' ]; then
echo "Shutdown the tomcat successfully!"
else
echo "Find tomcat is still running,kill it!"
ps -ef | grep ${sv}/bin | grep ${us} | grep -v grep | awk '{print $2}' | xargs kill -9
fi
if [ -f ${log} ]; then
echo "move the log to a new name..."
mv "$log" $log"_"${m_date}
fi
}
function restart_tm {
echo "begin to restart tomcat"
stop_tm
sleep 2
start_tm
}
function status_tm {
echo "The follows:"
if [ $(ps -ef | grep java | grep ${us} | grep ${sv}/bin | grep -v grep | wc -l) -eq '0' ]; then
echo "Tomcat is not running!"
exit 0
else
ps -ef | grep ${sv}/bin | grep -v grep
fi
}
#if the user is not root,exit
echo "check whether the user is ${us}"
USER_NOW=$(whoami)
if [ ${USER_NOW} = "${us}" ]; then
echo "You are ${us}."
else
echo "To execute this shell,you must be ${us}!"
exit 0
fi
if [ $# -eq 0 ]; then
log_tm
elif [ $# = 1 -a $1 = "start" ]; then
echo "Begin to start the tomcat ..."
start_tm
elif [ $# = 1 -a $1 = "stop" ]; then
echo "Begin to shutdown the tomcat ..."
stop_tm
elif [ $# = 1 -a $1 = "restart" ]; then
echo "Begin to restart the tomcat ..."
restart_tm
elif [ $# = 1 -a $1 = "status" ]; then
status_tm
elif [ $# = 1 -a $1 = "log" ]; then
if [ -f ${log} ]; then
tail -500f $log
else
echo "cannot find log..."
fi
else
echo "Your param is wrong!"
echo "usage:"
echo "$0 [ start | stop | restart | status | log ]"
echo "The default param: log"
exit 1
fi
echo "Finished!"
说明:
本脚本的示例用户为boss,其他用户执行脚本的时候比如root,为了避免权限混乱,脚本里进行了用户的判断控制。
另外,用脚本杀进程关闭的 时候进行了日志的截断,也就是mv日志为当前的时间后缀,下次启动往新空白日志里面写
脚本的参数 有 start stop restart status log
当然,脚本考虑的情况没有那么全面,基本够用(我线上环境用这个脚本足够用)