SoFunction
Updated on 2025-03-10

Shell script writing Nagios plug-in monitoring program resource usage


[root@center230 libexec]# catcomponent_resource.sh
#!/bin/sh
#author:yangrong
#date:2014-05-20
#mail:10286460@
 
#pragrom_list=(VueDaemon VueCenter VueAgentVueCache VueSERVER VUEConnector Myswitch Slirpvde)
pragrom_list=(VueDaemon VueCenter VueAgentVueCache VueSERVER)
 
#### Get CPU threshold and mem threshold ##########
case $1 in
 --cpu)
   cpu_crit=$2
  ;;
 --mem)
   mem_crit=$2
  ;;
esac
 
case $3 in
 --cpu)
   cpu_crit=$4
  ;;
 --mem)
   mem_crit=$4
  ;;
esac
 
 
 
###Judge the number of passed parameters. If it is not 4, the var value is 1, and var0 is normal####
if [[ $1 == $3  ]];then
       var=1  
elif [ $# -ne 4 ] ;then
       var=1
else
       var=0
fi
 
 
###Print error message
if [ $var -eq 1 ];then
   echo "Usage parament:"
   echo "    $0 [--cpu][--mem]"
   echo ""
   echo "Example:"
   echo "    $0 --cpu 50 --mem50"
   exit
fi
 
 
###Put non-existent processes into a variable
num=$(( ${#pragrom_list[@]}-1 ))
 
NotExist=""
for digit in `seq 0 $num`
do
 a=`ps -ef|grep -v grep |grep ${pragrom_list[$digit]}|wc -l`
  if[ $a -eq 0 ];then
    NotExist="$NotExist ${pragrom_list[$digit]}"
    unset pragrom_list[$digit]
  fi
done
#echo"pragrom_list=${pragrom_list[@]}"
 
 
 
####Compare the resources occupied by the process and the threshold size
cpu_use_all=""
mem_use_all=""
compare_cpu_temp=0
compare_mem_temp=0
for n in ${pragrom_list[@]}
do
  cpu_use=`top -b -n1|grep $n|awk '{print $9}'`
  mem_use=`top -b -n1|grep $n|awk '{print $10}'`
   if[[ $cpu_use == "" ]];then
       cpu_use=0
   fi
   if[[ $mem_use == "" ]];then
       mem_use=0
   fi
 
  compare_cpu=`echo "$cpu_use > $cpu_crit"|bc`
  compare_mem=`echo "$mem_use > $mem_crit"|bc` 
   if[[ $compare_cpu == 1  ]];then
       compare_cpu_temp=1
   fi
   if[[ $compare_mem == 1  ]];then
       compare_mem_temp=1
   fi
 
  cpu_use_all="${n}_cpu_use=${cpu_use}% ${cpu_use_all}"
  mem_use_all="${n}_mem_use=${mem_use}% ${mem_use_all}"
done
 
 
###If this variable has a value, it means there is a process down. The exit value is 2
if [[ "$NotExist" != ""]];then
 echo -e "Current ${NotExist} isdown.$cpu_use_all;$mem_use_all"
 exit 2
###If the CPU comparison value is 1, it means that a process occupies more than the threshold, and the exit value is 2.
elif [[ "$compare_cpu_temp" == 1]];then
   echo -e "$cpu_use_all;$mem_use_all"
   exit 2
 
##If the mem comparison value is 1, it means that the process mem occupies more than the threshold, and the exit value is 2.
elif [[ $compare_mem_temp == 1 ]];then
   echo -e "$cpu_use_all;$mem_use_all"
   exit 2
## Otherwise, it will output normally and output the CPU to memory ratio
else
   echo -e "$cpu_use_all;$mem_use_all"
   exit 0
fi