如何用脚本监控CPU温度?

wen 实用脚本 2

本文目录导读:

如何用脚本监控CPU温度?

  1. Linux 系统
  2. Windows 系统
  3. macOS 系统
  4. 高级功能:Web监控界面
  5. 注意事项

我来介绍几种在不同系统下监控CPU温度的脚本方法。

Linux 系统

基础Shell脚本(使用lm-sensors)

#!/bin/bash
# cpu_temp_monitor.sh
# 安装依赖(如果未安装)
# sudo apt-get install lm-sensors
# sudo sensors-detect
# 检测CPU温度
get_cpu_temp() {
    if command -v sensors &> /dev/null; then
        # 获取第一个CPU核心温度
        temp=$(sensors | grep -oP 'Package id 0:\s+\+\K[0-9.]+')
        if [ -z "$temp" ]; then
            # 备用方法:获取核心温度
            temp=$(sensors | grep -oP 'Core 0:\s+\+\K[0-9.]+')
        fi
        echo "$temp"
    else
        # 从/sys/class/thermal读取
        if [ -f /sys/class/thermal/thermal_zone0/temp ]; then
            temp=$(cat /sys/class/thermal/thermal_zone0/temp)
            temp=$(echo "scale=1; $temp/1000" | bc)
            echo "$temp"
        else
            echo "无法获取CPU温度"
        fi
    fi
}
# 监控并报警
monitor_temp() {
    local threshold=${1:-80}  # 默认阈值80°C
    while true; do
        temp=$(get_cpu_temp)
        echo "$(date '+%Y-%m-%d %H:%M:%S') - CPU温度: ${temp}°C"
        if (( $(echo "$temp > $threshold" | bc -l) )); then
            echo "⚠️ 警告:CPU温度超过阈值 ${threshold}°C!"
            # 可选:发送通知
            # notify-send "CPU温度警告" "当前温度: ${temp}°C"
        fi
        sleep 5
    done
}
# 使用示例
monitor_temp 85

Python脚本(更强大灵活)

#!/usr/bin/env python3
# cpu_temp_monitor.py
import psutil
import time
import logging
from datetime import datetime
class CPUTemperatureMonitor:
    def __init__(self, threshold=80, interval=5):
        self.threshold = threshold
        self.interval = interval
        self.setup_logging()
    def setup_logging(self):
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler('cpu_temp.log'),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger(__name__)
    def get_temperature(self):
        """获取CPU温度"""
        try:
            # 方法1:使用psutil
            temps = psutil.sensors_temperatures()
            if 'coretemp' in temps:
                # Intel CPU
                cores = temps['coretemp']
                return max([core.current for core in cores])
            elif 'acpitz' in temps:
                # 某些AMD或通用系统
                return temps['acpitz'][0].current
            else:
                return None
        except Exception as e:
            self.logger.error(f"温度读取错误: {e}")
            return None
    def check_threshold(self, temperature):
        """检查是否超过阈值"""
        if temperature and temperature > self.threshold:
            self.logger.warning(f"⚠️  CPU温度警告!当前温度: {temperature}°C,阈值: {self.threshold}°C")
            return True
        return False
    def run_monitor(self, duration=None):
        """运行监控"""
        self.logger.info(f"开始CPU温度监控(阈值: {self.threshold}°C,间隔: {self.interval}秒)")
        start_time = time.time()
        try:
            while True:
                if duration and time.time() - start_time > duration:
                    break
                temp = self.get_temperature()
                if temp:
                    self.logger.info(f"CPU温度: {temp:.1f}°C")
                    self.check_threshold(temp)
                else:
                    self.logger.warning("无法获取CPU温度数据")
                time.sleep(self.interval)
        except KeyboardInterrupt:
            self.logger.info("监控已停止")
# 使用示例
if __name__ == "__main__":
    monitor = CPUTemperatureMonitor(threshold=85, interval=10)
    monitor.run_monitor()  # 无期限运行
    # monitor.run_monitor(duration=3600)  # 运行1小时

轻量级一行命令监控

# 最简单的监控(每5秒显示一次)
watch -n 5 'sensors | grep "Package\|Core 0"'
# 输出到文件
while true; do echo "$(date) - $(sensors | grep 'Package id 0' | awk '{print $4}')" >> cpu_temp.log; sleep 5; done

Windows 系统

PowerShell脚本

# cpu_temp_monitor.ps1
function Get-CPUTemperature {
    try {
        # 使用WMI获取CPU温度(需要管理员权限)
        $temps = Get-WmiObject -Namespace "root\wmi" -Class "MSAcpi_ThermalZoneTemperature"
        if ($temps) {
            $tempCelsius = ($temps.CurrentTemperature / 10) - 273.15
            return [math]::Round($tempCelsius, 1)
        } else {
            # 备用方法:使用注册表(某些系统)
            $regPath = "HKLM:\HARDWARE\DESCRIPTION\System\CentralProcessor\0"
            $temp = (Get-ItemProperty -Path $regPath -Name "~Temperature" -ErrorAction SilentlyContinue)."~Temperature"
            if ($temp) {
                return [math]::Round($temp / 10, 1)
            }
        }
    } catch {
        return $null
    }
}
function Monitor-Temperature {
    param(
        [int]$Threshold = 80,
        [int]$Interval = 5
    )
    Write-Host "开始CPU温度监控 (阈值: ${Threshold}°C)" -ForegroundColor Cyan
    while ($true) {
        $temp = Get-CPUTemperature
        if ($temp) {
            $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            if ($temp -gt $Threshold) {
                Write-Host "$timestamp - 警告: CPU温度 ${temp}°C 超过阈值!" -ForegroundColor Red
                # 可选:弹出通知
                # [System.Windows.Forms.MessageBox]::Show("CPU温度: ${temp}°C", "温度警告")
            } else {
                Write-Host "$timestamp - CPU温度: ${temp}°C" -ForegroundColor Green
            }
        } else {
            Write-Host "无法获取CPU温度" -ForegroundColor Yellow
        }
        Start-Sleep -Seconds $Interval
    }
}
# 运行监控
Monitor-Temperature -Threshold 85 -Interval 10

macOS 系统

Shell脚本(使用osx-cpu-temp)

#!/bin/bash
# cpu_temp_monitor_mac.sh
# 安装依赖
# brew install osx-cpu-temp
MONITOR_TEMP() {
    local threshold=${1:-80}
    while true; do
        if command -v osx-cpu-temp &> /dev/null; then
            temp=$(osx-cpu-temp | grep -oE '[0-9.]+' | head -1)
        else
            # 使用系统命令
            temp=$(sudo powermetrics --samplers smc -i 1 -n 1 | grep "CPU die" | awk '{print $NF}' | tr -d '°C')
        fi
        echo "$(date '+%Y-%m-%d %H:%M:%S') - CPU温度: ${temp}°C"
        if (( $(echo "$temp > $threshold" | bc -l) )); then
            echo "⚠️ 警告:CPU温度过高!"
            osascript -e "display notification \"CPU温度: ${temp}°C\" with title \"温度警告\""
        fi
        sleep 5
    done
}
MONITOR_TEMP 85

高级功能:Web监控界面

from flask import Flask, jsonify
import psutil
import threading
import time
app = Flask(__name__)
cpu_temp_data = {'temperature': 0, 'timestamp': 0}
def monitor_thread():
    global cpu_temp_data
    while True:
        try:
            temps = psutil.sensors_temperatures()
            if 'coretemp' in temps:
                temp = max([core.current for core in temps['coretemp']])
            else:
                temp = 0
            cpu_temp_data = {
                'temperature': temp,
                'timestamp': time.time()
            }
        except:
            pass
        time.sleep(5)
@app.route('/')
def index():
    return '''
    <!DOCTYPE html>
    <html>
    <head>
        <title>CPU温度监控</title>
        <script>
            setInterval(function() {
                fetch('/api/temperature')
                    .then(response => response.json())
                    .then(data => {
                        document.getElementById('temp').textContent = 
                            data.temperature.toFixed(1) + '°C';
                    });
            }, 5000);
        </script>
    </head>
    <body>
        <h1>CPU温度监控</h1>
        <p>当前温度: <span id="temp">0°C</span></p>
    </body>
    </html>
    '''
@app.route('/api/temperature')
def get_temperature():
    return jsonify(cpu_temp_data)
if __name__ == '__main__':
    threading.Thread(target=monitor_thread, daemon=True).start()
    app.run(host='0.0.0.0', port=5000)

注意事项

  1. 权限问题:某些系统需要root/管理员权限
  2. 硬件支持:部分CPU或主板可能不支持温度读取
  3. 温度单位:确认读数单位(摄氏度/华氏度)
  4. 安全阈值:一般CPU安全温度范围:
    • 空闲:30-50°C
    • 负载:50-80°C
    • 警戒:80-90°C
    • 危险:>90°C

选择适合你系统的脚本,建议先在测试环境运行确认能正确读取温度。

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