Shell脚本如何模拟故障触发告警

wen 实用脚本 1

本文目录导读:

Shell脚本如何模拟故障触发告警

  1. 模拟系统资源故障
  2. 模拟服务故障
  3. 模拟磁盘故障
  4. 模拟网络故障
  5. 综合告警测试脚本
  6. 使用监控工具验证
  7. 注意事项

我来介绍几种在Shell脚本中模拟故障触发告警的常用方法:

模拟系统资源故障

CPU过载

#!/bin/bash
# 模拟CPU使用率过高
cpu_alert_threshold=80
# 方法1: 使用stress工具(需要先安装)
# stress --cpu 4 --timeout 60
# 方法2: 通过计算模拟CPU高负载
for i in $(seq 1 $(nproc)); do
    while true; do
        :
    done &
done
sleep 30  # 持续30秒
kill %1 2>/dev/null
# 检查CPU使用率并触发告警
cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
if (( $(echo "$cpu_usage > $cpu_alert_threshold" | bc -l) )); then
    echo "ALERT: CPU usage $cpu_usage% exceeded threshold $cpu_alert_threshold%"
    # 可以在这里调用告警系统
    # curl -X POST http://alert-system/api/alert
fi

内存不足

#!/bin/bash
# 模拟内存使用过高
mem_alert_threshold=90
# 分配大量内存
allocate_memory() {
    size=$1
    for i in $(seq 1 $size); do
        arr+=($(head -c 10M /dev/urandom))
    done
}
# 触发内存告警
mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
if (( $(echo "$mem_usage > $mem_alert_threshold" | bc -l) )); then
    echo "ALERT: Memory usage $mem_usage% exceeded threshold $mem_alert_threshold%"
    # 发送告警
fi

模拟服务故障

服务停止/崩溃

#!/bin/bash
# 模拟nginx服务故障
# 方法1: 停止服务
service nginx stop
# 或 systemctl stop nginx
# 方法2: 模拟进程崩溃
kill -9 $(pgrep nginx) 2>/dev/null
# 监控并触发告警
if ! pgrep -x "nginx" > /dev/null; then
    echo "ALERT: Nginx service is down!"
    # 重启服务并发送告警
    service nginx start
    echo "Nginx has been restarted"
fi

端口不可达

#!/bin/bash
# 模拟端口故障
port=8080
# 使用iptables阻止端口
iptables -A INPUT -p tcp --dport $port -j DROP
# 检测端口连通性
if ! nc -zv localhost $port 2>/dev/null; then
    echo "ALERT: Port $port is unreachable"
fi
# 清理iptables规则
iptables -D INPUT -p tcp --dport $port -j DROP

模拟磁盘故障

磁盘空间满

#!/bin/bash
# 模拟磁盘空间不足
disk_alert_threshold=80
# 创建大文件填充磁盘
dd if=/dev/zero of=/tmp/fake_disk_fill bs=1M count=1024  # 创建1GB文件
# 检查磁盘使用率
disk_usage=$(df -h / | awk 'NR==2 {print $5}' | cut -d'%' -f1)
if [ $disk_usage -gt $disk_alert_threshold ]; then
    echo "ALERT: Disk usage $disk_usage% exceeded threshold $disk_alert_threshold%"
fi
# 清理
rm -f /tmp/fake_disk_fill

I/O延迟模拟

#!/bin/bash
# 使用ionice和dd模拟磁盘I/O压力
for i in {1..5}; do
    dd if=/dev/zero of=/tmp/test_io_$i bs=1M count=100 &
done
wait
# 检查I/O等待时间
io_wait=$(iostat -c | awk 'NR==4 {print $4}')
if (( $(echo "$io_wait > 10" | bc -l) )); then
    echo "ALERT: High I/O wait time: $io_wait%"
fi
# 清理
rm -f /tmp/test_io_*

模拟网络故障

网络延迟/丢包

#!/bin/bash
# 模拟网络延迟和丢包
# 添加网络延迟
tc qdisc add dev eth0 root netem delay 1000ms
# 添加丢包
tc qdisc add dev eth0 root netem loss 50%
# 测试网络连通性
if ! ping -c 3 -W 5 google.com > /dev/null 2>&1; then
    echo "ALERT: Network connectivity issues detected"
fi
# 清理网络规则
tc qdisc del dev eth0 root netem

模拟DNS故障

#!/bin/bash
# 错误DNS配置
echo "nameserver 1.1.1.1" > /etc/resolv.conf  # 使用错误的DNS
# 检测DNS解析
if ! nslookup example.com > /dev/null 2>&1; then
    echo "ALERT: DNS resolution failed"
fi
# 恢复DNS配置
echo "nameserver 8.8.8.8" > /etc/resolv.conf

综合告警测试脚本

#!/bin/bash
# 综合故障模拟和告警系统
LOG_FILE="/var/log/alert_simulation.log"
ALERT_WEBHOOK="http://your-alert-system/api/alert"
log_alert() {
    local level=$1
    local message=$2
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message" | tee -a $LOG_FILE
    # 发送告警到外部系统
    # curl -X POST -H "Content-Type: application/json" \
    #      -d "{\"level\":\"$level\",\"message\":\"$message\"}" \
    #      $ALERT_WEBHOOK
}
cleanup() {
    echo "Cleaning up simulated faults..."
    rm -f /tmp/*_test_*
    tc qdisc del dev eth0 root netem 2>/dev/null
    kill %1 %2 2>/dev/null
}
trap cleanup EXIT
# 主测试流程
echo "Starting fault simulation test..."
# 模拟CPU过载
log_alert "WARNING" "Simulating CPU overload"
for i in $(seq 1 $(nproc)); do
    while true; do :; done &
done
sleep 5
kill %1 2>/dev/null
# 模拟内存压力
log_alert "WARNING" "Simulating memory pressure"
dd if=/dev/zero of=/tmp/mem_test bs=1M count=500 2>/dev/null &
sleep 3
kill %2 2>/dev/null
# 检查系统状态
cpu_load=$(uptime | awk -F'load average:' '{print $2}' | cut -d, -f1)
mem_free=$(free -m | grep Mem | awk '{print $4}')
disk_free=$(df -h / | awk 'NR==2 {print $4}')
log_alert "INFO" "System status after simulation: CPU load=$cpu_load, Free memory=${mem_free}MB, Free disk=$disk_free"
echo "Fault simulation completed. Check $LOG_FILE for details"

使用监控工具验证

#!/bin/bash
# 使用常用监控命令验证故障
echo "=== System Status Check ==="
# 1. 检查负载
echo "1. System Load:"
uptime
# 2. 检查内存
echo -e "\n2. Memory Usage:"
free -h
# 3. 检查磁盘
echo -e "\n3. Disk Usage:"
df -h
# 4. 检查进程
echo -e "\n4. Top Processes:"
ps aux --sort=-%cpu | head -5
# 5. 检查端口
echo -e "\n5. Listening Ports:"
ss -tlnp | head -10
# 6. 检查网络连接
echo -e "\n6. Network Connections:"
netstat -tun | head -5
# 7. 系统日志中的错误
echo -e "\n7. Recent Errors in System Log:"
journalctl -p err -n 5 --no-pager 2>/dev/null || dmesg | tail -5

注意事项

  1. 在测试环境执行:所有故障模拟操作最好在测试环境进行
  2. 设置超时机制:避免模拟故障持续影响系统
  3. 记录测试过程:详细记录模拟的故障类型和触发条件
  4. 准备恢复脚本:确保能快速恢复系统到正常状态
  5. 告警级别设置:区分WARNING、CRITICAL等告警级别

这些脚本可以帮助你测试告警系统的可靠性,确保在生产环境中能正确触发和处理各类故障告警。

抱歉,评论功能暂时关闭!