实践案例
- 1. 监控磁盘剩余空间,当低于20GB时发送警报邮件给管理员,并设置每日检查。
- 2. 检查Web服务是否运行(通过进程或端口),若未运行则启动服务并配置防火墙。
- 3. 使用Curl命令测试Web服务的可访问性,成功时返回确认信息,失败时返回特定的状态码。
- 4. 涉及的技术点
1. 监控磁盘剩余空间
free_space=$(df -h | grep /$ | awk '{print $4}' | cut -d 'G' -f 1)
if [ $free_space -lt 20 ]; then
echo "Disk space is below 20GB" | mail -s "Disk Space Warning" admin@test.com
else
echo "Free disk space: ${free_space}G"
fi
运行结果示例:
[root@localhost scripts]# bash disk_monitor.sh
[root@localhost scripts]# mail
Heirloom Mail version 12.5 7/5/10. Type ? for help.
"/var/spool/mail/root": 46 messages 1 new 43 unread
U 45 root Mon Jan 2 06:21 19/641 "Disk Space Warning"
N 46 root Mon Jan 2 22:30 18/631 "Disk Space Warning"
2. 检查Web服务状态
process_count=$(ps -ef | grep httpd | grep -v grep | wc -l)
# Alternatively, use netstat to check port 80
# process_count=$(netstat -lnupt | grep :80 | wc -l)
if [ $process_count -ne 0 ]; then
echo "HTTPD service is running."
else
echo "Starting HTTPD service..."
systemctl restart firewalld
firewall-cmd --add-port=80/tcp
systemctl start httpd
fi
Web服务正在运行:
[root@localhost scripts]# bash web_service_check.sh
HTTPD service is running.
Web服务未运行:
[root@localhost scripts]# bash web_service_check.sh
Starting HTTPD service...
Success
[root@localhost scripts]# firewall-cmd --list-ports
80/tcp
3. 使用Curl测试Web服务
curl -s http://192.168.6.20 > /dev/null
if [ $? -eq 0 ]; then
echo "Web server is running."
else
echo "Web server is not accessible."
exit 12
fi
服务正常访问:
[root@localhost scripts]# bash web_test.sh
Web server is running.
服务无法访问:
[root@localhost scripts]# bash web_test.sh
Web server is not accessible.
[root@localhost scripts]# echo $?
12
4. 技术点
- 修改系统时区
编辑系统环境变量文件
[root@localhost scripts]# vim /etc/profile
在文件末尾添加如下内容:
TZ='Asia/Shanghai'
export TZ
重新加载配置文件以应用更改:
[root@localhost scripts]# source /etc/profile
查看当前时区设置:
[root@localhost scripts]# date
Tue Jan 3 14:36:48 CST 2023
手动调整系统时间:
[root@localhost scripts]# date -s "2023-01-02 22:39:10"
[root@localhost scripts]# hwclock -w # 将系统时间写入硬件时钟