温馨提示×

centos cpustat怎么写脚本

小樊
36
2026-09-03 04:10:28
栏目: 智能运维

在 CentOS 上,如果你想用 cpustat 写监控脚本,一般分三步:
1️⃣ 安装 cpustat
2️⃣ 了解 cpustat 输出
3️⃣ 写 shell 脚本调用并分析

下面我一步步给你示例。


一、安装 cpustat

CentOS 默认可能没有 cpustat:

yum install epel-release -y
yum install cpustat -y

检查是否安装成功:

which cpustat

二、cpustat 基本用法

cpustat 1 5

含义:

  • 1:每 1 秒采样一次
  • 5:采样 5 次

示例输出:

CPU  usr  sys  idle  iowait
 0   12   5    80    3
 1   20   8    70    2

三、写一个基础监控脚本

示例 1:监控 CPU 使用率并记录到日志

#!/bin/bash

LOG=/var/log/cpu_monitor.log
INTERVAL=2
COUNT=10

echo "$(date) CPU 监控开始" >> $LOG

cpustat $INTERVAL $COUNT | while read line
do
    echo "$(date) $line" >> $LOG
done

echo "$(date) CPU 监控结束" >> $LOG

赋予执行权限:

chmod +x cpu_monitor.sh
./cpu_monitor.sh

四、进阶:超过阈值报警

示例 2:usr+sys > 90% 报警

#!/bin/bash

THRESHOLD=90
INTERVAL=1
COUNT=5

cpustat $INTERVAL $COUNT | awk -v threshold=$THRESHOLD '
NR>1 {
    usage = $2 + $3
    if (usage > threshold) {
        print "警告: CPU" $1 " 使用率 " usage "%"
    }
}'

五、后台长期运行(配合 crontab)

每天每 5 分钟记录一次:

crontab -e

添加:

*/5 * * * * /root/cpu_monitor.sh

六、常见问题

1️⃣ 没有 cpustat 命令

确认是否安装,或改用:

top -bn1 | head
mpstat 1 5

2️⃣ 想监控某个进程

建议用:

pidstat -u -p PID 1 5

如果你愿意,我可以帮你写:

  • ✅ 服务器巡检脚本
  • ✅ 邮件/钉钉报警
  • ✅ 多核 CPU 图形化统计

你主要用来 排查性能问题 还是 长期监控

0