Linux

SMART-отчёт по дискам

Проверяет здоровье, температуру и износ дисков через smartctl.

Python Linux Продвинутый
Скачать smart_report.py
Описание

Что делает скрипт

Скрипт получает список устройств через smartctl --scan и разбирает JSON-вывод SMART. Показываются модель, состояние, температура, часы работы, переназначенные и ожидающие сектора, ошибки CRC и износ SSD. Для доступа к SMART обычно нужен root.

Запуск

Быстрый старт

sudo python smart_report.py

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • sudo python smart_report.py
  • sudo python smart_report.py --device /dev/sda --json smart.json
  • sudo python smart_report.py --warn-temp 50
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
Linux sudo apt install python3
smartmontools smartctl
Linux sudo apt install smartmontools
Исходник

smart_report.py

#!/usr/bin/env python3
"""Отчёт SMART по дискам через smartctl."""
from __future__ import annotations

import argparse
import json
import shutil
import subprocess
from dataclasses import asdict, dataclass
from pathlib import Path


@dataclass
class DiskReport:
    device: str
    model: str
    health: str
    temperature: int | None
    power_on_hours: int | None
    reallocated: int | None
    pending: int | None
    uncorrectable: int | None
    crc_errors: int | None
    wear_level: int | None
    percentage_used: int | None
    errors: str


def run(argv: list[str]) -> subprocess.CompletedProcess[str]:
    return subprocess.run(argv, capture_output=True, text=True, check=False)


def scan_devices() -> list[tuple[str, str]]:
    result = run(["smartctl", "--scan", "-j"])
    devices: list[tuple[str, str]] = []
    try:
        data = json.loads(result.stdout)
    except json.JSONDecodeError:
        data = {}
    for item in data.get("devices", []):
        name = item.get("name")
        if name:
            devices.append((name, item.get("type", "")))
    if devices:
        return devices
    result = run(["smartctl", "--scan"])
    for line in result.stdout.splitlines():
        parts = line.split()
        if parts and parts[0].startswith("/dev/"):
            devices.append((parts[0], ""))
    return devices


def number(value) -> int | None:
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def parse_device(device: str, device_type: str, warn_temp: int) -> DiskReport:
    argv = ["smartctl", "-a", "-j"]
    if device_type:
        argv.extend(["-d", device_type])
    argv.append(device)
    result = run(argv)
    try:
        data = json.loads(result.stdout)
    except json.JSONDecodeError:
        error = result.stderr.strip() or result.stdout.strip() or "нет JSON-ответа"
        return DiskReport(device, "неизвестно", "unknown", None, None, None, None, None, None, None, None, error[:200])

    model = data.get("model_name") or data.get("device", {}).get("name") or "неизвестно"
    health_data = data.get("smart_status", {})
    passed = health_data.get("passed")
    health = "PASSED" if passed is True else "FAILED" if passed is False else "unknown"
    temperature = number(data.get("temperature", {}).get("current"))
    if temperature is None:
        temperature = number(data.get("nvme_smart_health_information_log", {}).get("temperature"))
    hours = number(data.get("power_on_time", {}).get("hours"))
    if hours is None:
        hours = number(data.get("nvme_smart_health_information_log", {}).get("power_on_hours"))

    attributes: dict[int, int | None] = {}
    for row in data.get("ata_smart_attributes", {}).get("table", []):
        identifier = number(row.get("id"))
        if identifier is None:
            continue
        raw = row.get("raw", {})
        attributes[identifier] = number(raw.get("value"))
        if attributes[identifier] is None:
            attributes[identifier] = number(str(raw.get("string", "")).split()[0])

    nvme = data.get("nvme_smart_health_information_log", {})
    errors = result.stderr.strip().splitlines()
    return DiskReport(
        device=device,
        model=model,
        health=health,
        temperature=temperature,
        power_on_hours=hours,
        reallocated=attributes.get(5),
        pending=attributes.get(197),
        uncorrectable=attributes.get(198),
        crc_errors=attributes.get(199),
        wear_level=attributes.get(177) or attributes.get(231),
        percentage_used=number(nvme.get("percentage_used")),
        errors=" | ".join(errors[:2])[:200],
    )


def main() -> int:
    parser = argparse.ArgumentParser(description="SMART-отчёт по дискам")
    parser.add_argument("--device", action="append", default=[], help="Устройство, можно несколько раз")
    parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
    parser.add_argument("--warn-temp", type=int, default=55, help="Порог температуры")
    args = parser.parse_args()

    if shutil.which("smartctl") is None:
        print("smartctl не найден. Установите smartmontools.")
        return 2

    if args.device:
        devices = [(item, "") for item in args.device]
    else:
        devices = scan_devices()

    if not devices:
        print("Диски не найдены. Запустите от root или укажите --device.")
        return 2

    reports = [parse_device(device, device_type, args.warn_temp) for device, device_type in devices]
    problems = 0

    for report in reports:
        print(f"== {report.device} ==")
        print(f"Модель:        {report.model}")
        print(f"Здоровье:      {report.health}")
        print(f"Температура:   {report.temperature if report.temperature is not None else '-'} C")
        print(f"Часы работы:   {report.power_on_hours if report.power_on_hours is not None else '-'}")
        print(f"Reallocated:   {report.reallocated if report.reallocated is not None else '-'}")
        print(f"Pending:       {report.pending if report.pending is not None else '-'}")
        print(f"Uncorrectable: {report.uncorrectable if report.uncorrectable is not None else '-'}")
        print(f"CRC errors:    {report.crc_errors if report.crc_errors is not None else '-'}")
        print(f"Износ:         {report.wear_level if report.wear_level is not None else '-'}")
        print(f"NVMe used:     {report.percentage_used if report.percentage_used is not None else '-'}%")
        if report.errors:
            print(f"smartctl:      {report.errors}")
        if report.health == "unknown":
            print("  [WARN] состояние SMART неизвестно")
            problems += 1
        if report.health == "FAILED":
            print("  [WARN] SMART сообщает об отказе")
            problems += 1
        if report.temperature is not None and report.temperature >= args.warn_temp:
            print(f"  [WARN] температура {report.temperature} C выше порога {args.warn_temp} C")
            problems += 1
        for label, value in (("reallocated", report.reallocated), ("pending", report.pending), ("uncorrectable", report.uncorrectable), ("CRC", report.crc_errors)):
            if value is not None and value > 0:
                print(f"  [WARN] {label}: {value}")
                problems += 1
        print()

    if args.json:
        args.json.write_text(json.dumps([asdict(item) for item in reports], ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
        print(f"JSON сохранён: {args.json}")

    return 1 if problems else 0


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get linux-smart-report
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Linux

Bash и Python для серверов, рабочих станций и повседневных задач Linux.