- 检测nginx进程是否存在异常
`#!/bin/bash
收集nginx进程pid
pid=$(ps -ef |grep nginx|grep worker|awk '{print $2}')
收集第一个nginx进程的pid,打上时间戳
pid0=$(ps -ef |grep nginx|grep worker|awk '{print $2}'|head -n 1)
starttime0=$(ps -o lstart= -p $pid0)
starttimestamp0=$(date -d "$starttime0" +%s)
result=""
判断每个pid是否与第一个的启动时间相等
for i in $pid ; do
starttime=$(ps -o lstart= -p $i)
starttimestamp=$(date -d "$starttime" +%s)
if [ $starttimestamp0 -eq $starttimestamp ];then
result+="ture"
else
result+="false"
fi
done
如果存在不同的则重载nginx
if [[ $result == "false" ]] ; then
echo "=发现nginx存在异常进程,正在重载="
/usr/sbin/nginx -s reload
else
echo "=nginx进程未发现异常="
fi
`
- 校验每个节点的配置是否一致
`#!/bin/bash
hosts=(18.12 18.13 18.14)
echo "=检测conf.d/下的文件="
for i in ${hosts[*]};do
递归计算目录中所有文件的MD5值
dir1="/usr/local/nginx/conf/conf.d"
dir2=ssh ${i} "cd /usr/local/nginx/conf/conf.d && pwd"
calculate_md5() {
local dir="$1"
find "$dir" -type f -exec md5sum {} ; | sort -k 2 | awk '{print $1}'
}
对比两个MD5列表是否一致
compare_md5() {
local list1="$1"
local list2="$2"
temp_file1=$(mktemp)
temp_file2=$(mktemp)
echo "$list1" > "$temp_file1"
echo "$list2" > "$temp_file2"
diff "$temp_file1" "$temp_file2" >/dev/null
rm -f "$temp_file1" "$temp_file2"
}
计算两个目录的MD5值并进行比较
md5_list1=$(calculate_md5 "$dir1")
md5_list2=$(calculate_md5 "$dir2")
if compare_md5 "$md5_list1" "$md5_list2"; then
echo "${i}的conf.d目录的文件一致"
else
echo "${i}的conf.d目录的文件不一致"
fi
done
echo "=检测nginx.conf="
Md5sum=md5sum /usr/local/nginx/conf/nginx.conf
echo -e "\n18.11nginx.conf的md5值:$Md5sum"
for i in ${hosts[*]};do
md5=`ssh ${i} "md5sum /usr/local/nginx/conf/nginx.conf"`
if [ "$Md5sum"x = "$md5"x ]; then
echo -e "\n${i}nginx.conf文件正常,正在重载"
ssh ${i} "/usr/sbin/nginx -s reload"
sleep 2
else
echo -e "\n${i}nginx.conf文件异常,请排查!!"
echo -e \n$md5
fi
done`
- 运行此脚本从svn更新配置,并调用上面两个脚本检测配置和进程
`#!/bin/bash
svn update更新nginx配置
cd /usr/local/nginx/conf && svn up
hosts=(18.12 18.13 18.14)
for i in ${hosts[*]};do
echo $i
ssh $i "cd /usr/local/nginx/conf && svn up"
sleep 2
done
sleep 15
调用脚本检查nginx配置、重载配置
sh /root/checkng/check_ngconf.sh
调用脚本检查nginx进程是否异常,异常则重载
echo -e "\n=检查18.11进程是否异常="
sh /root/checkng/ng_reload_check.sh
for i in ${hosts[*]};do
echo -e "\n=检查$i进程是否异常="
ssh $i "sh /root/checkng/ng_reload_check.sh"
don`