1. 磁盘剩余空间监控脚本
yum install mailx -y
编辑邮件配置文件 /etc/mail.rc
,添加以下内容:
set from=9*****@qq.com
set smtp=smtp.qq.com
set smtp-auth-user=9******@qq.com
set smtp-auth-password=o*********
set smtp-auth=login
创建磁盘监控脚本 disk1.sh
:
vim disk1.sh
添加以下内容:
#!/bin/bash
disk=$(df -m | grep -w "/" | tr -s " " | cut -d " " -f4)
str1="Warning: Disk space less than 20G!"
if [ "$disk" -lt 20000 ]; then
echo "$str1" | mail -s "$str1" 9*****@qq.com
fi
保存并退出编辑器。设置脚本可执行权限:
chmod +x disk1.sh
设置定时任务:
vim /etc/crontab
添加以下行:
0 0 * * * /root/disk1.sh
2. 检查Web服务状态并启动服务
创建检查和启动Web服务的脚本 web1.sh
:
vim web1.sh
添加以下内容:
#!/bin/bash
if ps -ef | grep -q "[h]ttpd"; then
echo "HTTPD is already running"
elif ss -lnt | grep -qw ":80"; then
echo "Port 80 is open, HTTPD might be running"
else
echo "HTTPD is not running, starting service..."
yum install httpd -y &> /dev/null
systemctl start httpd
systemctl start firewalld
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-port=80/tcp
firewall-cmd --reload
echo "HTTPD is now running!"
fi
保存并退出编辑器。设置脚本可执行权限:
chmod +x web1.sh
执行脚本web1.sh
bash web1.sh
执行结果
3. 使用curl命令检查Web服务可访问性
创建Web服务可访问性检查脚本 web2.sh
:
vim web2.sh
添加以下内容:
#!/bin/bash
if curl -s 192.168.160.130 > /dev/null; then
echo "web server is running"
else
echo "web not accessible"
exit 12
fi
保存并退出编辑器。设置脚本可执行权限:
chmod +x web2.sh
执行脚本
bash web2.sh
结果显示
手动运行脚本进行测试
bash disk1.sh
邮件收到系统预警