在 Debian 下如果你说的是 cpustat(通常来自 sysstat 包,或者是指 pidstat / mpstat 等工具),一般有两种常见理解:
mpstat / pidstat(很多人误叫 cpustat)cpustat 工具(by Colin Ian King)下面我分别给你写脚本的示例。
sudo apt update
sudo apt install sysstat
#!/bin/bash
# cpu_monitor.sh
INTERVAL=2
COUNT=5
echo "开始 CPU 监控..."
mpstat $INTERVAL $COUNT
运行:
chmod +x cpu_monitor.sh
./cpu_monitor.sh
#!/bin/bash
while true; do
mpstat 1 1 | awk '/Average:/ || /all/ {print $3, $5, $12}'
sleep 2
done
sudo apt install cpustat
sudo cpustat -T 1
#!/bin/bash
LOG=/var/log/cpu_usage.log
while true; do
echo "==== $(date) ====" >> $LOG
sudo cpustat -T 1 -n 1 >> $LOG
sleep 5
done
后台运行:
nohup ./cpu_log.sh &
#!/bin/bash
THRESHOLD=80
while true; do
cpu=$(mpstat 1 1 | awk '/all/ {print 100 - $12}')
int_cpu=${cpu%.*}
if [ "$int_cpu" -gt "$THRESHOLD" ]; then
echo "CPU 使用率过高: $cpu%" | mail -s "CPU Alert" admin@local
fi
sleep 10
done
cpustat 通常需要 rootsysstat 收集ls /var/log/sysstat
如果你能告诉我:
我可以直接帮你写一份可直接用的脚本。