最近有一个需求需要对服务器上的服务进行校验,我写了一个服务校验模板
后续对其他服务校验的可以基于当前这个脚本进行扩展:
1.config 文件定义了需要校验的服务
2.checkService.sh 定义了执行校验的脚本
config
#配置文件说明 #ip:服务:调用的函数:函数参数|返回的错误信息 2611:storm:checkStatusByNum:supervisor,1|storm(supervisor) 2611:storm:checkStatusByNum:supervisor,2|storm(supervisor) 2612:storm:checkStatusByNum:supervisor,2|storm(supervisor)
checkService.sh
#!/bin/bash groupArr=("mongo" "storm" "redis" "hadoop" "druid" "mysql") declare -A msgMap=() SUCCESS=0 FAILED=1 function checkStatusByNum(){ #函数有2个校验参数 #参数1: ps -ef 中填充的值 #参数2: (非必须) 服务的数量的预期个数 , 默认为1 expectNum=1 if [ $2 -ne $expectNum ]; then expectNum=$2 fi num=$(ps -ef | grep $1 | grep -v grep | wc -l) if [ $num -eq $expectNum ]; then return $SUCCESS else return $FAILED fi } function checkService(){ #函数有1个参数 #参数1: 校验的服务组 while read LINE do #先判断是否空行 if [[ -z $LINE ]]; then continue fi #常见的注释格式也不做处理 if [[ `echo $LINE | egrep '^(-|#)' | wc -l` -eq 1 ]]; then continue fi errMsg=`echo $LINE | cut -d '|' -f 2` service=`echo $LINE | cut -d '|' -f 1` OLD_IFS=$IFS IFS=":" arr=($service) IFS=$OLD_IFS serviceId=${arr[0]} group=${arr[1]} function=${arr[2]} argsBefore=${arr[3]} #判断是否是针对本机的监控 localId=`hostname | cut -d . -f 1` if [ $localId -ne $serviceId ]; then continue fi #判断是否是指定的服务组 #指定: 在 groupArr 中存在 且 配置文件中的服务组标识与执行脚本的参数一致 #不指定: 全部的服务(执行脚本不加额外的参数) flag=1 if [[ -n $1 ]]; then #echo $1 flag=0 for (( i=0; i<${#groupArr[@]}; i++)) do if [[ $1 == ${groupArr[i]} && $1 == $group ]]; then flag=1 break fi done fi if [[ $flag -eq 0 ]]; then continue fi #判断函数是否有参数 if [[ -n argsBefore ]]; then OLD_IFS=$IFS IFS="," args=($argsBefore) IFS=$OLD_IFS argsString="" for(( i=0; i<${#args[@]}; i++)); do argsString=$argsString" "${args[i]} done else continue fi echo "$function $argsString" $function $argsString info=$? # echo $info if [ $info -eq $FAILED ]; then msgMap[$group]=${msgMap[$group]}"&"$errMsg fi done < $(dirname $0)/config } checkService $1; for key in ${!msgMap[@]} do echo $key": "${msgMap[$key]} done