温馨提示×

debian cpustat怎么写脚本

小樊
38
2026-09-16 20:01:15
栏目: 智能运维

在 Debian 下如果你说的是 cpustat(通常来自 sysstat 包,或者是指 pidstat / mpstat 等工具),一般有两种常见理解:

  1. sysstat 里的 mpstat / pidstat(很多人误叫 cpustat)
  2. GitHub 上的 cpustat 工具(by Colin Ian King)

下面我分别给你写脚本的示例


一、使用 sysstat(最常见)

1️⃣ 安装

sudo apt update
sudo apt install sysstat

2️⃣ 用 mpstat 写监控脚本

#!/bin/bash

# cpu_monitor.sh
INTERVAL=2
COUNT=5

echo "开始 CPU 监控..."
mpstat $INTERVAL $COUNT

运行:

chmod +x cpu_monitor.sh
./cpu_monitor.sh

3️⃣ 只统计 CPU 使用率(脚本示例)

#!/bin/bash

while true; do
    mpstat 1 1 | awk '/Average:/ || /all/ {print $3, $5, $12}'
    sleep 2
done

二、使用 cpustat(Colin King 的版本)

1️⃣ 安装

sudo apt install cpustat

2️⃣ 基本用法

sudo cpustat -T 1

3️⃣ 写脚本(记录日志)

#!/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 &

三、简单判断 CPU 占用并报警(示例)

#!/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 通常需要 root
  • Debian 默认可能没开 sysstat 收集
    检查:
    ls /var/log/sysstat
    
  • 容器里可能没有完整 CPU 信息

如果你能告诉我:

  • 哪个 cpustat
  • 监控整机 / 某个进程 / 写日志 / 报警

我可以直接帮你写一份可直接用的脚本

0