【问题标题】:Script in ubuntu to take CPU temperature and CPU usage in the same time and save to file [closed]ubuntu中的脚本同时获取CPU温度和CPU使用率并保存到文件[关闭]
【发布时间】:2019-09-06 11:49:58
【问题描述】:

我需要在 Ubuntu 中编写脚本或命令行代码,这些代码从 lm_sensors 或类似的东西中获取 CPU 温度和 CPU 使用百分比,并且我想将此信息保存在 .txt 文件中,其中包含每次测量的日期和时间。我尝试编写下面的 .sh 文件,温度工作但 CPU 使用率无法正常工作,它每次只保存第一次测量。 有人可以帮助我吗?

while true;
do
  echo $( date '+%H:%M:%S' ): $( sensors | grep 'CPU Temperature' | sed -r 's/^.*:        +(.*)  +[(].*$/\1/' ) >> temperature.txt;
  echo $( date '+%H:%M:%S' ): $( top -b -n 1 | grep 'CPU:') >> cpu.txt;
  sleep 1; 
done

【问题讨论】:

  • “每次只保存第一次测量”是什么意思?
  • 我的意思是在 cpu.txt 文件中它每秒保存相同的 cpu 使用百分比。
  • 为什么会出错?你知道它改变的事实吗?
  • 这对我来说是错误的,因为我同时打开了 psensor 窗口,我看到这个值正在改变。
  • 这个问题很清楚,可以接受答案,所以应该重新打开它。

标签: linux bash ubuntu command line


【解决方案1】:

您可以这样计算 CPU 使用率,但只能随着时间的推移计算。 cpu使用率不存储在文件中,你必须自己计算:

cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5) "%"}'

如果您有 CPU 温度传感器,它位于 /sys/class/hwmon。您需要自己弄清楚哪一个是正确的,因为这取决于驱动程序。我猜是“coretemp”。

$ cat /sys/class/hwmon/hwmon*/name
acpitz
dell_smm
coretemp
nouveau

了解以上内容后,您可以执行以下操作:

#! /bin/bash

LOG=cpu.log
while true; do
    percentage=$(cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5) "%"}')
    echo -n "$(date "+%F-%T") " >> ${LOG}
    echo -n "$percentage " >> ${LOG}
    cat /sys/class/hwmon/hwmon2/temp1_input >> ${LOG}
done
exit 0
``

[1] [Getting cpu usage same every time.](https://unix.stackexchange.com/questions/69185/getting-cpu-usage-same-every-time)

【讨论】:

  • 这是我获取 CPU 温度的方式:sensors -j | jq --raw-output '."coretemp-isa-0000"."Core 0" | to_entries | .[] | select(.key | match("input")) | .value' 以摄氏度而不是原始值给出结果
  • Afaik,temp1_input 不是原始值,而是摄氏度 * 1000 的温度。它取决于芯片的准确度,但我认为它除以 1000 似乎没问题。我认为可以肯定地说传感器也使用 hwmon 中文件的输出,因为 sysfs (etc) 是内核的接口:-)
  • 感谢您的回答。如果它按我的意愿工作,我会在星期四试一试,我会告诉你的。 :)
  • 成功了,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-12
  • 1970-01-01
  • 2014-03-29
  • 2020-10-18
  • 1970-01-01
  • 2010-09-08
相关资源
最近更新 更多