我需要在 Ubuntu 中编写脚本或命令行代码,从 lm_sensors 或类似程序获取 CPU 温度和 CPU 使用率百分比。我希望将这些信息保存到 .txt 文件中,并附上每次测量的日期和时间。我尝试编写下面的 .sh 文件。但它无法按我想要的方式工作。有人能帮我吗?
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
答案1
Sysfs 是解析内核子系统公开的属性的更好的来源。
echo "scale=1; $(sort -nr /sys/class/hwmon/hwmon1/{temp1_input,temp2_input,temp3_input} | head -n1) / 1000" | bc
输出:
38.0
Linux CPU 利用率:
https://rosettacode.org/wiki/Linux_CPU_utilization#UNIX_Shell
#!/bin/bash
# by Paul Colby (http://colby.id.au), no rights reserved ;)
# Temperature inputs.
TEMP_INPUT=$(echo /sys/class/hwmon/hwmon1/{temp1_input,temp2_input,temp3_input})
PREV_TOTAL=0
PREV_IDLE=0
while true; do
# Get the total CPU statistics, discarding the 'cpu ' prefix.
CPU=(`sed -n 's/^cpu\s//p' /proc/stat`)
IDLE=${CPU[3]} # Just the idle CPU time.
# Calculate the total CPU time.
TOTAL=0
for VALUE in "${CPU[@]}"; do
let "TOTAL=$TOTAL+$VALUE"
done
# Calculate the CPU usage since we last checked.
let "DIFF_IDLE=$IDLE-$PREV_IDLE"
let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
# Calculate highest CPU Temperature.
HIGH_TEMP=$(echo "scale=1; $(sort -r $TEMP_INPUT | head -n1) / 1000" | bc)
# Redirect CPU temperature and % of CPU usage to file.
echo "$(date '+%H:%M:%S'): +${HIGH_TEMP}°C ${DIFF_USAGE}%" >> cpu.txt
# Remember the total and idle CPU times for the next check.
PREV_TOTAL="$TOTAL"
PREV_IDLE="$IDLE"
# Wait before checking again.
sleep 1
done
输出cpu.txt:
12:02:27:+38.0°C 6%