温馨提示×

如何定时跑debian cpustat

小樊
47
2026-10-10 12:54:13
栏目: 智能运维

在 Debian 上“定时跑 cpustat”通常有几种做法,取决于你是想周期性采集、写日志还是做监控。下面按常见场景给你几种方案。


一、先确认 cpustat 是否安装

cpustat 通常来自 sysstat 包:

sudo apt update
sudo apt install sysstat

验证:

which cpustat
cpustat 1 5

二、用 cron 定时执行(最常用)

1️⃣ 每分钟采集一次,写入日志

编辑当前用户的 cron:

crontab -e

添加:

* * * * * /usr/bin/cpustat 1 1 >> /var/log/cpustat.log 2>&1

含义:

  • 每分钟执行一次
  • 采集 1 秒、1 次
  • 追加到日志文件

2️⃣ 每 5 分钟采集一次(更常见)

*/5 * * * * /usr/bin/cpustat 5 1 >> /var/log/cpustat.log 2>&1

3️⃣ 带时间戳(推荐)

*/5 * * * * echo "=== $(date) ===" >> /var/log/cpustat.log; /usr/bin/cpustat 5 1 >> /var/log/cpustat.log

三、用 systemd timer(更现代)

1️⃣ 创建 service

sudo tee /etc/systemd/system/cpustat.service > /dev/null <<'EOF'
[Unit]
Description=Run cpustat

[Service]
Type=oneshot
ExecStart=/usr/bin/cpustat 5 1 >> /var/log/cpustat.log
EOF

2️⃣ 创建 timer

sudo tee /etc/systemd/system/cpustat.timer > /dev/null <<'EOF'
[Unit]
Description=Timer for cpustat

[Timer]
OnCalendar=*:0/5
Persistent=true

[Install]
WantedBy=timers.target
EOF

3️⃣ 启用

sudo systemctl daemon-reload
sudo systemctl enable --now cpustat.timer

查看状态:

systemctl list-timers | grep cpustat

四、如果只是想“持续监控 CPU 使用率”

你其实不一定需要 cpustat,可以用:

sar 1 0

或

mpstat 1

它们更适合长期监控。


五、日志轮转(防止日志爆炸)

sudo tee /etc/logrotate.d/cpustat > /dev/null <<'EOF'
/var/log/cpustat.log {
    weekly
    rotate 4
    compress
    missingok
    notifempty
}
EOF

六、总结建议

需求 推荐方式
简单定时采集 cron
系统级、可控 systemd timer
长期监控 sar / mpstat
写日志分析 cron + logrotate

如果你能告诉我:

  • 是服务器监控还是临时排查
  • 想采集哪些指标(CPU 占用 / 进程级)
  • 是否要汇总成报表

我可以帮你写一套更完整的方案。

0 踩