温馨提示×

debian cpustat能不能脚本

小樊
44
2026-10-13 12:11:55
栏目: 智能运维

可以的,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

示例:获取 1 秒内的平均 CPU 使用率

mpstat 1 1

脚本中提取数值(例如用户态 CPU)

#!/bin/bash

usage=$(mpstat 1 1 | awk '/Average:/ && $2 ~ /all/ {print 100 - $NF}')
echo "Idle CPU: $usage%"

三、纯 shell 脚本(不用任何工具)

如果你不想装软件,可以直接读 /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%"

四、定时脚本(cron 示例)

*/5 * * * * /root/cpu_check.sh >> /var/log/cpu.log

总结

方式 是否适合脚本 推荐度
cpustat ✅ 可以 ⭐⭐
mpstat ✅ 非常适合 ⭐⭐⭐⭐
/proc/stat ✅ 最灵活 ⭐⭐⭐⭐

如果你能说一下:

  • 是想实时监控 / 写日志 / 告警
  • 是单核还是多核
  • 是否允许安装软件

我可以帮你写一个完整可直接用的脚本。

0 踩