Skip to content

Instantly share code, notes, and snippets.

@ChinaXing
Created January 24, 2013 05:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChinaXing/4617859 to your computer and use it in GitHub Desktop.
Save ChinaXing/4617859 to your computer and use it in GitHub Desktop.
check_host : 检查服务器的网络链接和进程,输出json格式。可扩展
#!/bin/env bash
############################################################
#Author : ChinaXing - chen.yack@gmail.com
#Create : 2013-01-20 15:56
#Function : check hosts status
# 检查服务器状态:
# 1. 网络链接
# a. ESTAB链接列表
# b. LISTEN端口列表
# 2. 进程
# a. httpd,nginx,java,php进程列表
#Output : 1. json格式 { status : xxx , data : xxx }
# 2. status: success / error
# data : [
# { "NETSTAT" : {
# "LISTEN" : [ "...","..." ],
# "ESTABLISHED" : [ "...","..." ],
# }
# },
# { "PROCESS" : [
# " ... ", " ... "
# ]
# },
# ]
############################################################
PROCESS_CHECKED="nginx|httpd|java|php"
# 检查链接
function netstat
{
command netstat -anp 2>/dev/null | \
awk 'BEGIN{i=0;j=0;}
{
if($6 ~ /LISTEN/){
l[i++]=$1" "$4" "$5" "$7
}else if ($6 ~ /ESTABLISH/){
e[j++]=$1" "$4" "$5" "$7
}
}END{
print "\t{\n\t\"LISTEN\"",":[";
first=1;
for(i in l){
if(first){ printf "\n\t\t\"%s\"",l[i]; first=0}
else { printf "\n\t\t,\"%s\"",l[i]; }
}
print "\n\t\t],\n\t\"ESTABLISHED\"",":[";
first=1;
for(j in e){
if(first){ printf "\n\t\t\"%s\"",e[i]; first=0}
else { printf "\n\t\t,\"%s\"",e[i]; }
}
print "\n\t\t]\n\t}";
}'
# netstat exit status
return ${PIPSTATUS[1]} || $?
}
# 检查进程
function process
{
local first=1
echo -e "\t["
ps ax -ouser,command | \
grep -vw " grep " | grep -E -w "($PROCESS_CHECKED)" | \
while read line
do
if [ $first -eq 1 ]
then
first=0
echo $'\t'$'\t'"\"$line\""
else
echo $'\t'$'\t',"\"$line\""
fi
done
echo -e "\t]"
}
#######################################
#
############## main ###################
#
#######################################
# proccess
if PROCESS=$(process)
then
echo '"PROCESS" : " { "status" : "success" , "data" : '
echo "$PROCESS"
echo '}'
else
echo '"PROCESS" : " { "status" : "error" , "data" : "fetch process info failed" }'
fi
# netstat
if NETSTAT=$(netstat)
then
echo '"NETSTAT" : " { "status" : "success" , "data" : '
echo "$NETSTAT"
echo '}'
else
echo '"NETSTAT" : " { "status" : "error" , "data" : "fetch network info failed" }'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment