脚本如何检测硬件温度告警

wen 实用脚本 1

本文目录导读:

脚本如何检测硬件温度告警

  1. 核心思路
  2. 方案一:Linux 环境 (最常用)
  3. 方案二:Windows 环境
  4. 方案三:macOS 环境
  5. 实现持续监控 (Crontab / 任务计划)
  6. 总结要点

检测硬件温度(如CPU、GPU、硬盘)并触发告警,通常需要通过操作系统提供的接口或第三方工具来获取传感器的读数,脚本(如 Shell、Python、PowerShell)本身无法直接读取硬件寄存器,必须依赖这些底层工具。

以下是针对不同操作系统的主流检测方法和脚本示例:

核心思路

  1. 获取温度数据:使用命令行工具(如 sensorswmicosx-cpu-temp)或读取伪文件系统(如 /sys/class/thermal)。
  2. 解析输出:提取出具体的温度数值(如 75.0°C)。
  3. 设置阈值:定义正常、警告、严重等告警级别(CPU > 80°C 告警,> 90°C 严重)。
  4. 触发动作:输出告警、发送邮件/通知、记录日志、甚至执行关机脚本。

Linux 环境 (最常用)

Linux 下最通用的工具是 lm-sensors (监控CPU/主板) 和 hddtemp/smartctl (监控硬盘),或者直接读取 /sys/class/thermal/thermal_zone*/temp

准备工作:安装工具

sudo apt-get install lm-sensors hddtemp smartmontools  # Debian/Ubuntu
sudo yum install lm_sensors hddtemp smartmontools      # CentOS/RHEL
# 配置传感器 (通常选yes即可)
sudo sensors-detect

Shell 脚本示例:检查CPU与硬盘温度并告警

#!/bin/bash
# --- 配置阈值 ---
CPU_WARN=75      # 警告温度 (°C)
CPU_CRIT=90      # 严重温度
HDD_WARN=50
HDD_CRIT=60
# --- 告警函数 ---
send_alert() {
    local level=$1
    local component=$2
    local temp=$3
    echo "[$level] $component 温度过高: $temp°C! 时间: $(date)" >> /var/log/temp_alert.log
    # 可以在此处添加发送邮件或短信的命令, 
    # echo "警告: $component 温度 $temp°C" | mail -s "服务器温度告警" admin@example.com
}
# --- 1. 检查CPU温度 (依赖 sensors 命令) ---
if command -v sensors &> /dev/null; then
    # 提取所有含 "°C" 的行,并提取数字. 常见输出: "Package id 0:  +45.0°C"
    cpu_temp=$(sensors -u | grep -oP 'temp1_input:\s*\K[0-9.]+' | head -1 | awk '{print int($1)}')
    # 或者更简单的: cp_temp=$(sensors | grep 'Package id 0' | awk '{print $4}' | tr -d '+°C' | cut -d'.' -f1)
    # sensors 输出中没有 "Package id 0", 尝试从 /sys 读取 (Intel)
    if [ -z "$cpu_temp" ] && [ -f /sys/class/thermal/thermal_zone0/temp ]; then
        cpu_temp=$(($(cat /sys/class/thermal/thermal_zone0/temp) / 1000))
    fi
    # 判断 (如果温度不为空且是数字)
    if [ -n "$cpu_temp" ] && [ "$cpu_temp" -eq "$cpu_temp" ] 2>/dev/null; then
        if [ "$cpu_temp" -ge "$CPU_CRIT" ]; then
            send_alert "CRITICAL" "CPU" "$cpu_temp"
        elif [ "$cpu_temp" -ge "$CPU_WARN" ]; then
            send_alert "WARNING" "CPU" "$cpu_temp"
        else
            echo "CPU温度正常: $cpu_temp°C"
        fi
    else
        echo "无法获取CPU温度"
    fi
fi
# --- 2. 检查硬盘温度 (依赖 hddtemp 或 smartctl) ---
# 假设硬盘设备为 /dev/sda (请根据实际调整)
DISK_DEV="/dev/sda"
if command -v hddtemp &> /dev/null; then
    # 输出示例: /dev/sda: WDC WD40EFAX-68JH4N1: 34°C
    hdd_temp=$(sudo hddtemp "$DISK_DEV" | awk -F': ' '{print $3}' | tr -d '°C')
    if [ -n "$hdd_temp" ] && [ "$hdd_temp" -ge 0 ] 2>/dev/null; then
        if [ "$hdd_temp" -ge "$HDD_CRIT" ]; then
            send_alert "CRITICAL" "HDD $DISK_DEV" "$hdd_temp"
        elif [ "$hdd_temp" -ge "$HDD_WARN" ]; then
            send_alert "WARNING" "HDD $DISK_DEV" "$hdd_temp"
        fi
    fi
fi
# --- 3. 检查NVIDIA GPU温度 (如果有N卡) ---
if command -v nvidia-smi &> /dev/null; then
    gpu_temp=$(nvidia-smi --query-gpu=temperature.gpu --format=csv,noheader,nounits | head -1)
    if [ -n "$gpu_temp" ] && [ "$gpu_temp" -ge 80 ]; then
        send_alert "WARNING" "GPU" "$gpu_temp"
    fi
fi

Windows 环境

Windows 下比较理想的工具是 wmic (对某些硬件支持有限) 或者小巧的第三方工具 OpenHardwareMonitor 的命令行版,以及 CoreTempPowerShell 是主要脚本环境。

使用 WMIC 获取 (简单但可能不准)

# 获取CPU温度 (通过 WMI 中的 MSAcpi_ThermalZoneTemperature 类)
$temp = Get-WmiObject -Namespace "root/wmi" -Class "MSAcpi_ThermalZoneTemperature" | Select-Object -ExpandProperty "CurrentTemperature"
if ($temp) {
    $celsius = [math]::Round(($temp / 10) - 273.15, 1)
    Write-Host "CPU温度: $celsius °C"
    if ($celsius -gt 85) {
        Write-Warning "CPU温度过高! 当前温度: $celsius °C"
        # 添加告警动作: 发送邮件, 记录事件日志等
        # Write-EventLog -LogName Application -Source "TempMonitor" -EntryType Warning -EventId 1001 -Message "CPU温度 $celsius"
        # Send-MailMessage -To "admin@..."
    }
} else {
    Write-Host "无法通过WMI获取CPU温度(可能不支持)"
}

注意: 很多Windows主板的ACPI温度传感器不标准,WMIC可能返回 0 或者无法获取,更可靠的方法是用第三方工具。

使用 CoreTemp + 脚本 (推荐)

  1. 下载安装 CoreTemp(免费、轻量)。
  2. 在 CoreTemp 设置中启用 "Allow remote connections from other computers"输出到文件 (它可以在本地开启一个 HTTP 服务,或者将数据写入注册表/文件)。
  3. PowerShell 脚本示例 (读取 CoreTemp 的注册表数据):
# CoreTemp 默认将温度写入注册表
$basePath = "HKCU:\Software\CoreTemp"
$coreCount = (Get-ItemProperty -Path $basePath -Name "CoreCount" -ErrorAction SilentlyContinue).CoreCount
if ($coreCount -gt 0) {
    Write-Host "检测到 $coreCount 个核心"
    for ($i = 0; $i -lt $coreCount; $i++) {
        $tempPath = "$basePath\Core $i"
        $temp = (Get-ItemProperty -Path $tempPath -Name "Temp" -ErrorAction SilentlyContinue).Temp
        if ($temp -ne $null) {
            Write-Host "核心 $i 温度: $temp °C"
            if ($temp -gt 85) {
                Write-Warning "核心 $i 温度过高! 触发告警."
                # 此处可进行自动关机或告警动作
                # Restart-Computer -Force (危险操作, 慎用)
            }
        }
    }
} else {
    Write-Host "CoreTemp 未运行或未安装."
}

使用 OpenHardwareMonitor

这是最强大的方案,但需要下载其命令行组件 OpenHardwareMonitorCLI.exe

REM 下载 OpenHardwareMonitorCLI 并解压
REM 从 https://openhardwaremonitor.org/downloads/ 下载
REM 使用命令输出所有传感器
OpenHardwareMonitorCLI.exe -s
REM 输出示例:  
REM /intelcpu/0/temperature/0 45.0 °C
REM /intelcpu/0/temperature/1 35.0 °C
REM PowerShell 脚本可以解析 stdout

macOS 环境

macOS 下最轻量的是 osx-cpu-temp,或者用 powermetrics

使用 osx-cpu-temp (需要 Homebrew)

# 安装
brew install osx-cpu-temp
# 脚本
temp=$(osx-cpu-temp -C -F 2>/dev/null | grep -oE '[0-9]+' | head -1)
if [ "$temp" -gt 80 ]; then
   echo "警告: CPU温度 $temp°C" | osascript -e 'display notification "CPU温度过高!"'
   # 或利用 macOS 的 logger
   logger -p user.warning "CPU温度过高: $temp°C"
fi

使用 powermetrics (自带,但需sudo)

# 获取最近一次采样 (大约需要2秒)
temp=$(sudo powermetrics --samplers smc -n 1 -i 50ms 2>/dev/null | grep -i "CPU die temperature" | awk '{print $NF}' | tr -d 'C')
if [ -n "$temp" ] && [ "$temp" -gt 80 ]; then
   echo "CPU温度过高: $temp°C"
fi

实现持续监控 (Crontab / 任务计划)

脚本写好之后,放入定时任务或计划任务中,每隔一段时间(如5分钟)运行一次。

Linux (Crontab)

# 每5分钟执行一次
*/5 * * * * /home/user/temp_monitor.sh

Windows (任务计划程序)

使用 PowerShell 脚本,创建基本任务,触发器设置为“每天”,并选择“重复任务每隔 5 分钟”。

总结要点

  1. 依赖工具:脚本无法裸读温度,必须依赖 sensorswmicCoreTemp 等。
  2. 解析输出:不同版本的工具输出格式可能不同,脚本需要容错,最好用正则 grep -oP 提取整数。
  3. 阈值设定:CPU/GPU 长期 < 85°C 算正常,> 90°C 需要告警;机械硬盘 < 45°C,固态硬盘 < 60°C。
  4. 权限问题:读取某些传感器可能需要 root(Linux)或管理员权限(Windows wmic/OpenHardwareMonitor),脚本可能需要 sudo 或以管理员身份运行。
  5. 告警执行动作:不要仅仅在终端打印,应该写入日志、发送邮件、桌面通知或触发系统关机,并根据严重程度分级(如超过临界值自动关机保护硬件)。

抱歉,评论功能暂时关闭!