可以的,cpustat(通常指 Debian/Ubuntu 上的 cpustat 工具,或者你指的是 mpstat / /proc/stat 统计)完全可以用在脚本里。下面分几种情况说明。
cpustat(package: cpustat)Debian 里有一个工具叫 cpustat(由 cpustat 包提供,作者是 Colin Ian King)。
cpustat 1 5
表示每 1 秒采样一次,共 5 次。
#!/bin/bash
LOG=/var/log/cpu_usage.log
cpustat 1 10 >> "$LOG"
⚠️ 注意:
cpustat 输出是人类可读格式,不适合直接做数值计算mpstat(sysstat)如果你是为了写脚本取 CPU 使用率,更推荐 mpstat:
apt install sysstat
mpstat 1 1
#!/bin/bash
usage=$(mpstat 1 1 | awk '/Average:/ && $2 ~ /all/ {print 100 - $NF}')
echo "Idle CPU: $usage%"
如果你不想装软件,可以直接读 /proc/stat:
#!/bin/bash
read cpu a b c d e f g h < /proc/stat
idle1=$d
total1=$((a+b+c+d+e+f+g+h))
sleep 1
read cpu a b c d e f g h < /proc/stat
idle2=$d
total2=$((a+b+c+d+e+f+g+h))
idle=$((idle2-idle1))
total=$((total2-total1))
cpu_usage=$((100*(total-idle)/total))
echo "CPU usage: $cpu_usage%"
*/5 * * * * /root/cpu_check.sh >> /var/log/cpu.log
| 方式 | 是否适合脚本 | 推荐度 |
|---|---|---|
| cpustat | ✅ 可以 | ⭐⭐ |
| mpstat | ✅ 非常适合 | ⭐⭐⭐⭐ |
| /proc/stat | ✅ 最灵活 | ⭐⭐⭐⭐ |
如果你能说一下:
我可以帮你写一个完整可直接用的脚本。