通过Shell脚本监控服务器状态是一种常见的自动化运维任务。以下是一个基本的示例,展示如何使用Shell脚本来监控服务器的CPU使用率、内存使用率和磁盘空间。
#!/bin/bash
# 获取当前日期和时间
echo "Server Monitoring Report - $(date)"
# 监控CPU使用率
cpu_usage=$(top -bn1 | grep load | awk '{printf("CPU Load: %.2f%%\n", $(NF-2))}')
echo "$cpu_usage"
# 监控内存使用率
memory_usage=$(free | grep Mem | awk '{printf("Memory Usage: %.2f%%\n", $3/$2 * 100.0)}')
echo "$memory_usage"
# 监控磁盘空间
disk_usage=$(df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ printf("Disk Usage: %s/%s (%.2f%%)\n", $3, $2, $5) }')
echo "$disk_usage"
# 检查磁盘空间是否超过90%
threshold=90
echo "Checking disk space usage..."
if [[ $(echo "$disk_usage" | awk '{print $5}' | cut -d'%' -f1) -gt $threshold ]]; then
echo "Warning: Disk space usage is above the threshold!"
fi
# 检查CPU使用率是否超过80%
cpu_threshold=80
if [[ $(echo "$cpu_usage" | awk '{print $4}' | cut -d'%' -f1) -gt $cpu_threshold ]]; then
echo "Warning: CPU usage is above the threshold!"
fi
# 检查内存使用率是否超过80%
memory_threshold=80
if [[ $(echo "$memory_usage" | awk '{print $4}' | cut -d'%' -f1) -gt $memory_threshold ]]; then
echo "Warning: Memory usage is above the threshold!"
fi
echo "Monitoring complete."
date命令获取当前日期和时间,并打印出来。top命令获取CPU负载,并通过awk提取并格式化输出。free命令获取内存使用情况,并通过awk提取并格式化输出。df命令获取磁盘使用情况,并通过awk提取并格式化输出。monitor.sh。chmod +x monitor.sh
./monitor.sh
如果你希望定期运行这个脚本,可以使用cron来实现。例如,每小时运行一次:
cron任务:crontab -e
0 * * * * /path/to/monitor.sh >> /var/log/monitor.log 2>&1
这行配置表示每小时的第0分钟运行monitor.sh脚本,并将输出重定向到/var/log/monitor.log文件。通过这种方式,你可以自动化地监控服务器的状态,并在出现问题时及时收到通知。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。