要将 cpustat
集成到脚本中,首先需要确保你的系统中已经安装了 sysstat
包,因为 cpustat
是这个包的一部分。在 Debian 系统中,你可以使用以下命令来安装它:
sudo apt update
sudo apt install sysstat
安装完成后,你可以将 cpustat
命令集成到脚本中。以下是一些示例:
创建一个名为 monitor_cpu.sh
的脚本文件,并添加以下内容:
#!/bin/bash
# 使用 cpustat 监控 CPU 使用情况,每秒更新一次,共更新 5 次
cpustat -u 1 5
然后,给脚本添加执行权限并运行它:
chmod +x monitor_cpu.sh
./monitor_cpu.sh
如果你想将 cpustat
的输出保存到一个文件中,可以修改脚本如下:
#!/bin/bash
# 将 cpustat 的输出保存到文件 cpu_usage.log 中
cpustat -u 1 5 > cpu_usage.log
你可以使用 awk
、grep
等工具来解析 cpustat
的输出,并根据需要进行处理。例如,以下脚本将计算平均 CPU 使用率:
#!/bin/bash
# 使用 cpustat 获取 CPU 使用情况,并通过 awk 计算平均使用率
average_cpu_usage=$(cpustat -u 1 5 | awk '/Average:/ {print $NF}')
echo "Average CPU Usage: $average_cpu_usage%"
你可以创建一个循环来定期检查 CPU 使用率,并在超过某个阈值时发送警报。例如:
#!/bin/bash
# 设置 CPU 使用率阈值
threshold=80
while true; do
# 获取当前 CPU 使用率
current_usage=$(cpustat -u 1 1 | awk '/Average:/ {print $NF}' | cut -d'.' -f1)
# 检查是否超过阈值
if [ "$current_usage" -gt "$threshold" ]; then
echo "Alert: CPU usage is above $threshold%!"
# 在这里添加发送警报的代码,例如发送邮件或短信
fi
# 等待一段时间后再次检查
sleep 60
done
请注意,这个脚本会无限循环运行,直到你手动停止它。你可以根据需要调整循环间隔和警报逻辑。
通过这些示例,你应该能够根据自己的需求将 cpustat
集成到脚本中。