对传感器的输出进行着色

对传感器的输出进行着色

我过去sensors常常关注控制台上的 CPU 温度。这是输出的一部分:

coretemp-isa-0001
Adapter: ISA adapter
Physical id 1:  +45.0°C  (high = +80.0°C, crit = +90.0°C)
Core 0:         +39.0°C  (high = +80.0°C, crit = +90.0°C)
Core 1:         +39.0°C  (high = +80.0°C, crit = +90.0°C)
Core 2:         +40.0°C  (high = +80.0°C, crit = +90.0°C)
Core 3:         +38.0°C  (high = +80.0°C, crit = +90.0°C)
Core 4:         +40.0°C  (high = +80.0°C, crit = +90.0°C)
Core 8:         +39.0°C  (high = +80.0°C, crit = +90.0°C)
Core 9:         +38.0°C  (high = +80.0°C, crit = +90.0°C)
Core 10:        +38.0°C  (high = +80.0°C, crit = +90.0°C)
Core 11:        +39.0°C  (high = +80.0°C, crit = +90.0°C)
Core 12:        +39.0°C  (high = +80.0°C, crit = +90.0°C)

nouveau-pci-0200
Adapter: PCI adapter
GPU core:     +0.92 V  (min =  +0.92 V, max =  +1.00 V)
fan1:        2220 RPM
temp1:        +48.0°C  (high = +95.0°C, hyst =  +3.0°C)
                       (crit = +105.0°C, hyst =  +5.0°C)
                       (emerg = +135.0°C, hyst =  +5.0°C)

我想对这个输出进行“着色”。特别是,如果温度高于某个阈值,我希望它们显示为红色。因此,举例来说,假设阈值是 60,那么+60.0°C+61.0°C+62.0°C等的任何出现都应该为红色(理想情况下,我想要基于两个不同阈值的橙色级别和红色级别,但单级解决方案也会很棒)。理想情况下,这也应该适用于watch sensors.

答案1

用法: sensors | ./color_sensors.awk

与手表配合使用: watch -c 'sensors | ./color_sensors.awk'

#!/usr/bin/awk -f

BEGIN {
    DEFAULT_COLOR = "\033[;m";
    RED           = "\033[1;31m";
    MAGENTA       = "\033[1;35m";

    # CPU_thresholds
    cpu_high = 60; 
    cpu_middle = 50; 

    # GPU_thresholds
    gpu_high = 80; 
    gpu_middle = 70; 
}

function colorize(temp, mid_trsh, high_trsh) {
    new_color = "";  

    temp_number = temp;
    gsub("[^0-9]","",temp_number);
    gsub(".$","",temp_number);

    if(temp_number >= high_trsh) 
        new_color = RED;
    else if (temp_number >= mid_trsh) 
        new_color = MAGENTA;

    return new_color temp DEFAULT_COLOR;
}

/Core/          { $3 = "\t" colorize($3, cpu_middle, cpu_high); }
/Physical id/   { $4 = "\t" colorize($4, cpu_middle, cpu_high); }
# Multiple spaces added for alignment here - "\t      ".
/temp1/         { $2 = "\t      " colorize($2, gpu_middle, gpu_high) " "; }
                { print; }

结果: 在此输入图像描述

相关内容