在Debian系统中,cpustat
是一个用于显示CPU统计信息的工具,它是 sysstat
包的一部分。如果你想要自动化 cpustat
的执行,你可以使用多种方法,比如编写 shell 脚本、使用 cron 作业或者 systemd 定时器。以下是一些基本的步骤来实现自动化:
cpustat_monitor.sh
。nano cpustat_monitor.sh
#!/bin/bash
# 设置cpustat的输出文件路径
output_file="/var/log/cpustat.log"
# 获取当前日期和时间
date=$(date '+%Y-%m-%d %H:%M:%S')
# 执行cpustat命令并将输出追加到文件中
cpustat -u -p ALL $date >> $output_file
保存并关闭文件。
给脚本添加执行权限:
chmod +x cpustat_monitor.sh
./cpustat_monitor.sh
打开终端。
输入 crontab -e
来编辑当前用户的 crontab 文件。
添加一行来设置定时任务。例如,如果你想每5分钟运行一次脚本,你可以添加:
*/5 * * * * /path/to/cpustat_monitor.sh
Cron 将根据你设置的时间间隔自动执行脚本。
/etc/systemd/system/cpustat_monitor.service
:[Unit]
Description=CPUs statistics monitor
[Service]
Type=simple
ExecStart=/path/to/cpustat_monitor.sh
[Install]
WantedBy=timers.target
/etc/systemd/system/cpustat_monitor.timer
:[Unit]
Description=Run cpustat_monitor.service every 5 minutes
[Timer]
OnBootSec=5min
OnUnitActiveSec=5min
Unit=cpustat_monitor.service
[Install]
WantedBy=timers.target
systemctl enable --now cpustat_monitor.timer
Systemd 将根据你设置的定时器配置自动执行服务。
记得将 /path/to/cpustat_monitor.sh
替换为你的脚本实际路径。这些方法可以帮助你自动化 cpustat
的执行,以便定期收集CPU统计信息。