用Shell语言写一个Linux服务器巡检脚本,巡检到异常,发送邮箱通知
时间: 2024-03-09 17:47:23 浏览: 114
java实现对服务器的自动巡检邮件通知
好的,以下是一个Shell脚本示例,用于巡检Linux服务器并在发现异常时发送电子邮件通知。
```bash
#!/bin/bash
# set email recipient(s)
email_recipient="your.email@example.com"
# set subject for email notification
subject="Linux Server Status Alert"
# get system uptime
uptime=$(uptime)
# check disk usage and send email if usage exceeds 80%
disk_usage=$(df -h | awk '{print $5 " " $6}' | sed 's/%//g')
while read -r output; do
usage=$(echo $output | awk '{ print $1}' )
partition=$(echo $output | awk '{ print $2}' )
if [ $usage -ge 80 ]; then
echo "WARNING: Disk usage for \"$partition\" is at $usage%"
echo "WARNING: Disk usage for \"$partition\" is at $usage%" | mail -s "$subject" "$email_recipient"
fi
done <<< "$disk_usage"
# check CPU usage and send email if usage exceeds 80%
cpu_usage=$(top -bn1 | grep load | awk '{printf "%.2f\n", $(NF-2)}')
if (( $(echo "$cpu_usage > 0.80" | bc -l) )); then
echo "WARNING: CPU usage is at $cpu_usage%"
echo "WARNING: CPU usage is at $cpu_usage%" | mail -s "$subject" "$email_recipient"
fi
# check memory usage and send email if usage exceeds 80%
mem_usage=$(free -m | awk '/Mem:/ { printf("%.2f"), $3/$2*100 }')
if (( $(echo "$mem_usage > 80" | bc -l) )); then
echo "WARNING: Memory usage is at $mem_usage%"
echo "WARNING: Memory usage is at $mem_usage%" | mail -s "$subject" "$email_recipient"
fi
# check for failed login attempts and send email if attempts exceed 5
failed_attempts=$(grep "Failed password" /var/log/auth.log | wc -l)
if [ $failed_attempts -ge 5 ]; then
echo "WARNING: There have been $failed_attempts failed login attempts"
echo "WARNING: There have been $failed_attempts failed login attempts" | mail -s "$subject" "$email_recipient"
fi
```
该脚本将检查磁盘使用情况、CPU使用情况、内存使用情况和失败的登录尝试,并在任何一项超过预设阈值时发送电子邮件警报。您需要将脚本中的电子邮件收件人和主题更改为适合您自己的值,并确保在服务器上安装了邮件客户端(例如sendmail或postfix)以便发送电子邮件。
阅读全文