linux监测服务器状态并使用mail发送邮件的代码?
时间: 2023-06-08 10:04:49 浏览: 139
以下是一个简单的Shell脚本示例,可用于监测服务器状态并在发生问题时发送邮件:
```
#!/bin/bash
# Set email address to receive alerts
EMAIL=your_email@domain.com
# Set threshold for CPU usage and free disk space
CPU_THRESHOLD=80
DISK_THRESHOLD=10
# Check CPU usage
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}')
if [ ${CPU_USAGE%.*} -gt $CPU_THRESHOLD ]; then
echo "High CPU usage detected: $CPU_USAGE%"
echo "Server: $(hostname)" | mail -s "High CPU Usage Alert" $EMAIL
fi
# Check disk space usage
DISK_USAGE=$(df -h / | awk '/\// {print $(NF-1)}')
if [ ${DISK_USAGE%/*} -lt $DISK_THRESHOLD ]; then
echo "Low disk space detected: $DISK_USAGE%"
echo "Server: $(hostname)" | mail -s "Low Disk Space Alert" $EMAIL
fi
```
该脚本使用top命令检查CPU使用率并使用df命令检查磁盘空间使用率。如果任一阈值超过给定的阈值,则脚本将通过电子邮件通知指定的电子邮件地址。可以使用crontab将此脚本设置为定期运行。
阅读全文