You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
shell-project/os-test/monitor.sh

74 lines
2.3 KiB

2 years ago
#!/usr/bin/bash
# 定义解释型的信息
# Author: SZ2201班全体同仁,联系 newrain_wang@163.com
# 监控报警脚本
# 做mysql、nginx服务存活性检测、重要配置文件防篡改。
# mysql 主机 password,在生产中的脚本要写普通用户
mysqlPassword="QianFeng@123"
mysqlUser="root"
# 监控间隔
checkInterval=30
# 配置文件列表
configFile=("/etc/passwd" "/etc/sudoers" "/etc/hosts" "/etc/resolv.conf" "/etc/sysctl.conf")
hashFile=/tmp/.hashfile
# nginx 检查URL
nginxPath="/index.html"
# 出现异常,发送邮件通知
# 安装软件mailx
# 下列内容填写到 /etc/mail.rc
<<!
发送邮件的邮箱
set from=newrain_wang@163.com
邮箱服务器
set smtp=smtp.163.com
邮箱验证
set smtp-auth-user=newrain_wang@163.com
授权码,在官方站点中获取
set smtp-auth-password=NBVRUYYHYANZNUCL
set smtp-auth=login
set ssl-verify=ignore
!
# 测试发送邮件
# 每隔60秒执行一次检查
while :
do
# 检查mysql存活,通过对mysql进行sql语句的执行,来判断是否正常工作
mysql -u${mysqlUser} -p${mysqlPassword} -e "select now()" &>/dev/null
if [ $? -ne 0 ];then
mysql_error="mysql异常\n"
fi
# 检查nginx是否存活,通过访问nginx的服务来判断是否正常工作
code=$(curl -I -s http://127.0.0.1${nginxPath} |grep "HTTP/1.1" |awk '{print $2}')
<<!
httpcode 200 成功 301 临时重定向 302 永久重定向
!
if [ ! "$code" == "200" ] && [ ! "$code" == "301" ] && [ ! "$code" == "302" ];then
nginx_error="nginx访问异常\n"
fi
# 配置文件篡改检查
if [ "$1" == 'init' ];then
# 初始化,如果发现篡改,但是经过证实,是自己人做的,那么可以重新初始化
md5sum ${configFile[@]} > ${hashFile}
exit 0
fi
md5sum -c ${hashFile} 2>/dev/null |grep "FAILED" &>/dev/null
if [ $? -eq 0 ];then
checkFile_error="文件被篡改,请检查\n"
fi
# 如果错误信息变量被赋值至少一个,则邮件通知管理员进行处理。
if [ -n "$mysql_error" ] || [ -n "$nginx_error" ] || [ -n "$checkFile_error" ];then
echo ${mysql_error}${nginx_error}${checkFile_error}
echo -e "[`date +%F_%T`] 错误:\n${mysql_error}${nginx_error}${checkFile_error}" | mailx -s "报警通知" 1161733918@qq.com
fi
sleep ${checkInterval}
done