在Ubuntu系统中,cpustat 是一个非常有用的工具,用于实时监控CPU的使用情况。如果你想要实现自动化监控,可以考虑以下几种方法:
cron 定时任务你可以使用 cron 来定期运行 cpustat 并将输出保存到文件中。
打开终端并输入 crontab -e 来编辑当前用户的 cron 任务。
添加一行来定义定时任务。例如,每5分钟运行一次 cpustat 并将输出追加到 /var/log/cpustat.log 文件中:
*/5 * * * * /usr/bin/cpustat -c 1 >> /var/log/cpustat.log 2>&1
这里 -c 1 表示每秒采样一次,共采样5次(即每5分钟)。你可以根据需要调整这些参数。
保存并退出编辑器。新的 cron 任务会自动生效。
systemd 定时器如果你的系统使用 systemd,你可以创建一个 systemd 定时器来定期运行 cpustat。
创建一个新的 systemd 服务文件,例如 /etc/systemd/system/cpustat.service:
[Unit]
Description=Run cpustat periodically
[Service]
ExecStart=/usr/bin/cpustat -c 1 > /var/log/cpustat.log
创建一个新的 systemd 定时器文件,例如 /etc/systemd/system/cpustat.timer:
[Unit]
Description=Run cpustat every 5 minutes
[Timer]
OnBootSec=5min
OnUnitActiveSec=5min
Persistent=true
[Install]
WantedBy=timers.target
启用并启动定时器:
sudo systemctl enable --now cpustat.timer
watch 命令你也可以编写一个简单的脚本来定期运行 cpustat,并使用 watch 命令来实时查看输出。
#!/bin/bash
while true; do
clear
/usr/bin/cpustat -c 1
sleep 300 # 每5分钟运行一次
done
将这个脚本保存为 monitor_cpu.sh,然后使用以下命令运行:
chmod +x monitor_cpu.sh
./monitor_cpu.sh
如果你需要更复杂的监控和报警功能,可以考虑使用第三方监控工具,如Prometheus、Grafana等。这些工具可以集成 cpustat 并提供丰富的监控和可视化功能。
cpustat 的数据。通过这些方法,你可以实现Ubuntu系统中CPU使用情况的自动化监控。选择哪种方法取决于你的具体需求和偏好。