开发工具

基础资源监控

1. CPU 使用率监控

#!/bin/bash
# 监控CPU使用率,超过阈值发送告警

threshold=80  # 设置CPU使用率阈值(%)

# 获取当前CPU使用率(取用户+系统占用)
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}' | cut -d'.' -f1)

if [ "$cpu_usage" -gt "$threshold" ]; then
    echo "[警告] CPU使用率过高: ${cpu_usage}% at $(date)" >> /var/log/system_monitor.log
    # 发送邮件或Slack通知(需配置通知工具)
    # mail -s "CPU告警" admin@example.com <<< "CPU使用率: ${cpu_usage}%"
fi


2. 内存监控

#!/bin/bash
# 监控内存和Swap使用情况

# 获取内存使用率
mem_total=$(free -m | awk '/Mem:/ {print $2}')
mem_used=$(free -m | awk '/Mem:/ {print $3}')
mem_percent=$((mem_used*100/mem_total))

# 获取Swap使用率
swap_used=$(free -m | awk '/Swap:/ {print $3}')

if [ "$mem_percent" -gt 90 ]; then
    echo "[警告] 内存使用率: ${mem_percent}% at $(date)" >> /var/log/system_monitor.log
fi

if [ "$swap_used" -gt 1024 ]; then  # 如果Swap使用超过1GB
    echo "[警告] Swap使用量过高: ${swap_used}MB at $(date)" >> /var/log/system_monitor.log
fi


3. 磁盘空间监控

#!/bin/bash
# 监控磁盘使用率,默认检查根目录

threshold=90  # 磁盘使用率阈值(%)

# 获取根分区使用率
disk_usage=$(df -h / | awk 'NR==2 {print $5}' | tr -d '%')

if [ "$disk_usage" -ge "$threshold" ]; then
    echo "[警告] 磁盘空间不足: ${disk_usage}% at $(date)" >> /var/log/system_monitor.log
    # 可选:自动清理7天前的日志
    # find /var/log -name "*.log" -mtime +7 -exec rm -f {} \;
fi