怎样用脚本监控硬盘温度?

wen 实用脚本 2

本文目录导读:

怎样用脚本监控硬盘温度?

  1. Linux 系统脚本
  2. Windows 系统 (PowerShell)
  3. macOS 系统
  4. 跨平台 Python 脚本
  5. 安装依赖
  6. 设置定时任务
  7. 使用建议

我来介绍几种在不同操作系统中监控硬盘温度的脚本方法。

Linux 系统脚本

使用 smartctl 监控

#!/bin/bash
# 硬盘温度监控脚本 - smartctl.sh
# 检查是否安装了 smartctl
if ! command -v smartctl &> /dev/null; then
    echo "请先安装 smartmontools: sudo apt-get install smartmontools"
    exit 1
fi
# 获取所有硬盘设备
DISKS=$(lsblk -d -o name | grep -E '^(sd|nvme|hd)')
echo "=== 硬盘温度监控 ==="
echo "时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo ""
for disk in $DISKS; do
    temp=$(smartctl -A /dev/$disk | grep -i temperature | awk '{print $10}')
    if [ -n "$temp" ]; then
        echo "硬盘 /dev/$disk: ${temp}°C"
    else
        echo "硬盘 /dev/$disk: 无法获取温度"
    fi
done

使用 hddtemp 监控(较老的工具)

#!/bin/bash
# 使用 hddtemp 监控
# 安装: sudo apt-get install hddtemp
# 运行需要root权限
echo "硬盘温度:"
hddtemp /dev/sd? /dev/nvme?n? 2>/dev/null || echo "请安装 hddtemp 或以 root 运行"

持续监控并报警

#!/bin/bash
# 持续监控脚本
# 配置
WARN_TEMP=55     # 警告温度
CRIT_TEMP=65     # 临界温度
CHECK_INTERVAL=300  # 检查间隔(秒)
LOG_FILE="/var/log/disk_temp.log"
# 监控函数
monitor_temp() {
    while true; do
        timestamp=$(date '+%Y-%m-%d %H:%M:%S')
        for disk in /dev/sd? /dev/nvme?n?; do
            if [ -e "$disk" ]; then
                temp=$(smartctl -A "$disk" | grep -i temperature | awk '{print $10}')
                if [ -n "$temp" ]; then
                    echo "$timestamp $disk: ${temp}°C" >> "$LOG_FILE"
                    if [ "$temp" -gt "$CRIT_TEMP" ]; then
                        echo "⚠️ 严重: $disk 温度 $temp°C 超过临界值 $CRIT_TEMP°C"
                        # 发送警报(根据需要修改)
                        # mail -s "硬盘温度警告" admin@example.com <<< "警告信息"
                    elif [ "$temp" -gt "$WARN_TEMP" ]; then
                        echo "⚠️ 警告: $disk 温度 $temp°C 超过警告值 $WARN_TEMP°C"
                    fi
                fi
            fi
        done
        sleep $CHECK_INTERVAL
    done
}
# 运行监控
monitor_temp

Windows 系统 (PowerShell)

使用 WMI 监控

# 硬盘温度监控脚本 - disk_temp.ps1
# 获取硬盘温度
$disks = Get-WmiObject -Namespace "root\wmi" -Class MSStorageDriver_ATAPISmartData
Write-Host "=== 硬盘温度监控 ==="
Write-Host "时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')`n"
foreach ($disk in $disks) {
    $temp = $disk.Temperature
    if ($temp -ne $null) {
        Write-Host "硬盘 $($disk.InstanceName): ${temp}°C"
    }
}

使用第三方工具(如 smartctl for Windows)

# 下载 smartmontools for Windows 后使用
$smartctl = "C:\Program Files\smartmontools\bin\smartctl.exe"
$drives = Get-WmiObject Win32_DiskDrive | Select-Object -ExpandProperty DeviceID
foreach ($drive in $drives) {
    $output = & $smartctl -A $drive
    if ($output -match "Temperature.*?(\d+)") {
        Write-Host "$drive : $($matches[1])°C"
    }
}

macOS 系统

#!/bin/bash
# macOS 硬盘温度监控
# 使用 smartctl(需要 brew install smartmontools)
echo "硬盘温度监控:"
diskutil list | grep "/dev/disk" | while read disk; do
    dev=$(echo $disk | awk '{print $1}')
    temp=$(smartctl -A $dev | grep "Temperature" | awk '{print $10}')
    if [ -n "$temp" ]; then
        echo "$dev 温度: ${temp}°C"
    fi
done
# 或使用系统工具
sudo powermetrics --samplers smc -i 1000 -n 1 | grep "CPU die temperature" 2>/dev/null

跨平台 Python 脚本

#!/usr/bin/env python3
# disk_temp_monitor.py
import subprocess
import platform
import json
from datetime import datetime
def get_linux_temps():
    """获取 Linux 系统硬盘温度"""
    temps = {}
    try:
        # 获取所有块设备
        disks = subprocess.check_output(
            "lsblk -d -o name | grep -E '^(sd|nvme)'", 
            shell=True, text=True
        ).strip().split('\n')
        for disk in disks:
            if disk:
                try:
                    output = subprocess.check_output(
                        f"smartctl -A /dev/{disk}", 
                        shell=True, text=True
                    )
                    temp = None
                    for line in output.split('\n'):
                        if 'temperature' in line.lower():
                            temp = line.split()[-1]
                            break
                    if temp:
                        temps[disk] = f"{temp}°C"
                except:
                    temps[disk] = "无法读取"
    except:
        pass
    return temps
def get_windows_temps():
    """获取 Windows 系统硬盘温度(需管理员权限)"""
    temps = {}
    try:
        import wmi
        c = wmi.WMI()
        for disk in c.Win32_DiskDrive():
            temps[disk.Model] = "使用 WMI 获取"
    except:
        temps['Windows'] = "需要安装 pywin32"
    return temps
def get_macos_temps():
    """获取 macOS 系统硬盘温度"""
    temps = {}
    try:
        disks = subprocess.check_output(
            "diskutil list | grep /dev/disk", 
            shell=True, text=True
        ).strip().split('\n')
        for disk in disks:
            dev = disk.split()[0]
            try:
                output = subprocess.check_output(
                    f"smartctl -A {dev}", 
                    shell=True, text=True
                )
                temp = None
                for line in output.split('\n'):
                    if 'Temperature' in line:
                        temp = line.split()[-1]
                        break
                if temp:
                    temps[dev] = f"{temp}°C"
            except:
                temps[dev] = "无法读取"
    except:
        pass
    return temps
def main():
    system = platform.system()
    print(f"=== 硬盘温度监控 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===\n")
    if system == 'Linux':
        temps = get_linux_temps()
    elif system == 'Windows':
        temps = get_windows_temps()
    elif system == 'Darwin':  # macOS
        temps = get_macos_temps()
    else:
        print(f"不支持的系统: {system}")
        return
    if temps:
        for device, temp in temps.items():
            print(f"硬盘 {device}: {temp}")
    else:
        print("未检测到硬盘温度信息")
    # 可以保存到 JSON 文件
    with open('disk_temps.json', 'a') as f:
        data = {
            'timestamp': datetime.now().isoformat(),
            'temps': temps
        }
        f.write(json.dumps(data) + '\n')
if __name__ == "__main__":
    main()

安装依赖

Linux

# Debian/Ubuntu
sudo apt-get install smartmontools hddtemp
# CentOS/RHEL
sudo yum install smartmontools

Windows

macOS

brew install smartmontools

设置定时任务

Linux (crontab)

# 每5分钟检查一次
*/5 * * * * /path/to/disk_temp_monitor.sh
# 每天上午9点生成报告
0 9 * * * /path/to/temp_report.sh

Windows (任务计划程序)

# 创建定时任务
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\path\to\disk_temp.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 9am
Register-ScheduledTask -TaskName "DiskTempMonitor" -Action $action -Trigger $trigger

使用建议

  1. 确保以 root/管理员权限运行(访问 SMART 数据需要)

  2. 正常硬盘温度范围

    • 机械硬盘:30-50°C
    • SSD:30-65°C
    • 超过 60°C 建议关注
  3. 温度过高处理

    • 检查散热风扇
    • 清理灰尘
    • 增加散热措施
    • 减少硬盘工作量

需要更具体的配置或功能吗?

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