以下是一个简单的 shell 脚本示例,用于监控 cpu 使用率并根据设定的阈值执行操作:
#!/bin/bash # 设置阈值 THRESHOLD=80 # 无限循环,每隔一段时间检查一次 CPU 使用率 while true; do # 使用 mpstat 获取 CPU 使用率 cpu_usage=$(mpstat 1 1 | awk '/Average:/ {print $12}' | cut -d'.' -f1) # 检查 CPU 使用率是否超过阈值 if [ $cpu_usage -gt $THRESHOLD ]; then echo "CPU usage is above the threshold: $cpu_usage%" # 在此处执行你的操作,例如发送通知、重启服务等 else echo "CPU usage is normal: $cpu_usage%" fi # 等待一段时间(例如 60 秒)再次检查 sleep 60 done
将此脚本保存为 monitor_cpu.sh,然后通过运行 chmod x monitor_cpu.sh 使其可执行。最后,使用 ./monitor_cpu.sh 运行脚本。
请注意,这个脚本使用了 mpstat 命令,它也是 sysstat 包的一部分。如果尚未安装,请使用 sudo yum install sysstat 安装。
你可以根据需要修改阈值、检查间隔和执行的操作。