题目要求:
写一个shell脚本,通过curl -I 返回状态码来判定所访问的网站是否正常,比如当代码状态200,才算正常
写一个发邮件的脚本
实验:
(1)创建触发器及邮件报警测试
[root@localhost ~]# wget http://caspian.dotconf.net/menu/Software/SendEmail/sendEmail-v1.56.tar.gz
[root@localhost ~]# tar -zxvf sendEmail-v1.56.tar.gz
sendEmail-v1.56/
sendEmail-v1.56/CHANGELOG
sendEmail-v1.56/README
sendEmail-v1.56/README-BR.txt
sendEmail-v1.56/TODO
sendEmail-v1.56/sendEmail
sendEmail-v1.56/sendEmail.pl
[root@localhost ~]# cp sendEmail-v1.56/sendEmail /usr/local/bin/
[root@localhost ~]# chmod 755 /usr/local/bin/sendEmail
[root@localhost ~]# vi /opt/sendEmail.sh
[root@localhost ~]# vim /opt/sendEmail.sh
#!/bin/bash
#
# Filename: SendEmail.sh
# Revision: 1.0
# Date: 2020/08/26
# Author: Qicheng
# Email:
# Website: http://51xit.top/
# Description: 邮件告警脚本
# Notes: 使用sendEmail
#
# 脚本的日志文件
LOGFILE="/tmp/Email.log"
:>"$LOGFILE"
exec 1>"$LOGFILE"
exec 2>&1
SMTP_server='smtp.qq.com' # SMTP服务器,变量值需要自行修改
username='XXXX@qq.com' # 用户名,变量值需要自行修改
password='password' # 密码(QQ邮箱用的是授权码),变量值需要自行修改
from_email_address='XXXX@qq.com' #### 发件人Email地址,变量值需要自行修改
to_email_address="$1" # 收件人Email地址,传入的第一个参数
message_subject_utf8="$2" # 邮件标题,传入的第二个参数
message_body_utf8="$3" # 邮件内容,传入的第三个参数
# 转换邮件标题为GB2312,解决邮件标题含有中文,收到邮件显示乱码的问题。
message_subject_gb2312=`iconv -t GB2312 -f UTF-8 << EOF $message_subject_utf8 EOF`
[ $? -eq 0 ] && message_subject="$message_subject_gb2312" || message_subject="$message_subject_utf8"
# 转换邮件内容为GB2312,解决收到邮件内容乱码
message_body_gb2312=`iconv -t GB2312 -f UTF-8 << EOF $message_body_utf8 EOF`
[ $? -eq 0 ] && message_body="$message_body_gb2312" || message_body="$message_body_utf8"
# 发送邮件
sendEmail='/usr/local/bin/sendEmail'
set -x
$sendEmail -s "$SMTP_server" -xu "$username" -xp "$password" -f "$from_email_address" -t "$to_email_address" -u "$message_subject" -m "$message_body" -o message-content-type=text -o message-charset=gb2312
[root@localhost ~]# chmod +x /opt/sendEmail.sh
[root@localhost ~]# /opt/sendEmail.sh xxxxxx@qq.com 测试 测试
注意:上面脚本要自行修改的参数如下
(2)创建监控脚本
[root@localhost ~]# vim /opt/123.sh
#!/bin/bash
url='www.51xit.top'
sta=`curl -I $url 2>/dev/null |head -1 |awk '{print $2}'`
if [ $sta != "200" ]
then
/opt/sendEmail.sh xxxxx@qq.com "$url down." "$url down."
fi
[root@localhost ~]# chmod +x /opt/123.sh