Giter Club home page Giter Club logo

smartie's Introduction

SMARTie logo

SMARTie

This is a pure-python, 0-dependency library for getting basic disk information such as model, serial number, disk health, temperature, and SMART data. It supports both SCSI/ATA and NVMe devices.

It provides a high-level abstraction to enumerate devices and retrieve basic details, a low-level interface for sending raw SCSI/ATA commands, and a command-line tool for quickly getting information about your disks.

Usage

API Usage

High-level usage is simple:

from smartie.device import get_all_devices

for device in get_all_devices():
    # open the device first
    with device as d:
        print(d.path)
        print(d.model)
        print(d.serial)
        print(d.temperature)

        for attribute in d.smart_table.values():
            print(attribute.name, attribute.current_value)

Drop down a level if you want and send raw SCSI commands, such as an INQUIRY:

import ctypes

from smartie.scsi import structures
from smartie.device import get_device

with get_device('\\.\PhysicalDrive0') as device:
    # The structure that will be populated with the response.
    inquiry = structures.InquiryResponse()
  
    sense = device.issue_command(
        structures.Direction.FROM,
        structures.InquiryCommand(
            operation_code=structures.OperationCode.INQUIRY,
            allocation_length=ctypes.sizeof(inquiry)
        ),
        inquiry
    )
  
    print(inquiry.product_identification)

Or send an NVME IDENTIFY command:

import ctypes

from smartie.nvme import structures
from smartie.device import get_device

with get_device('/dev/nvme0') as device:
    # The structure that will be populated with the response.
    data = structures.NVMEIdentifyResponse()
    device.issue_admin_command(
        structures.NVMEAdminCommand(
            opcode=structures.NVMEAdminCommands.IDENTIFY,
            addr=ctypes.addressof(data),
            data_len=ctypes.sizeof(data),
            cdw10=1
        )
    )
    print(data.model_number)

Command Line Usage

Want to get JSON output to use with other programs? Use the command-line tools under smartie api, such as list to enumerate devices:

> sudo smartie api list
[
    {
        "model": "WD_BLACK SN770 2TB",
        "path": "/dev/nvme0n1",
        "serial": "<redacted>",
        "temperature": 52
    },
    {
        "model": "Samsung SSD 860 EVO 1TB",
        "path": "/dev/sdb",
        "serial": "<redacted>",
        "temperature": 27
    },
    {
        "model": "Samsung SSD 860 EVO 1TB",
        "path": "/dev/sdc",
        "serial": "<redacted>",
        "temperature": 28
    },
    {
        "model": "WD_BLACK SN770 2TB",
        "path": "/dev/nvme1n1",
        "serial": "<redacted>",
        "temperature": 46
    },
    {
        "model": "Samsung SSD 860 EVO 1TB",
        "path": "/dev/sda",
        "serial": "<redacted>",
        "temperature": 26
    }
]

Are you a human and just want to see your disk details? Take a look at smartie enumerate and smartie details:

cli_details_scsi.png

How about a developer trying to build a tool? You can use smartie dump to get access to raw responses from the disk as a table or binary:

cli_dump_nvme.png

Support

OS SCSI/ATA Supported NVME Supported Notes
Linux Yes Yes SG_IO v3 (Linux 2.6+)
Windows Yes In-progress
OS X In-progress* N/A *IDENTITY and SMART-related commands only.

OS X explicitly denies access to SCSI/ATA pass-through, except for IDENTITY and some SMART-related commands, so this is all we can support. Work for OS X is currently in-progress.

Installation

SMARTie currently requires Python 3.8 or greater.

pip install smartie

If you want the command line tools, you'll also want to do:

pip install smartie[cli]

FAQ

This library isn't returning any of my drives?

The APIs this library uses to communicate with devices typically require root (on Linux) or administrator (on Windows) access to work.

My drive doesn't work with this library?

Support for drives that don't follow modern standards is still a work in progress. Open an issue.

Library Y does X, can I copy that code?

It depends. This library is available under the MIT license and is a fun side project. I want anyone to be able to use it. Many existing projects are GPL or LGPL, so you need to avoid them when contributing to this project. Instead:

  • Use the specifications or vendor documentation whenever possible.
  • Use the SG_IO documentation by Danny (https://sg.danny.cz/sg/).
  • Use the conversations in mailing lists and bug trackers, while avoiding the code.

Does this library support RAID controllers?

Untested. It hasn't been thoroughly tested with RAID controllers, as the target audience for the main program that uses this library is consumer desktops. Patches happily accepted if you have one to test with!

ATA, ATAPI, SCSI, NVMe, what?

Acronyms, acronyms everywhere! What does any of this mean?

  • ATA: Advanced Technology Attachment.
  • ATAPI: AT Attachment Packet Interface.
  • SCSI: Small Computer System Interface.
  • NVMe: Non-Volatile Memory Express. The standard for connecting "modern" solid-state drives to a computer, typically through PCI-e.
  • SATA: Serial ATA.
  • PATA: Parallel ATA.
  • S.M.A.R.T: Self-Monitoring, Analysis, and Reporting Technology. A standard for hard drives and solid-state drives to report their health and status.

smartie's People

Contributors

jackeichen avatar tktech avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

jackeichen mewmix

smartie's Issues

Implement BeOS/Haiku support

Haiku supports all of the interfaces we require for basic support, but has little documentation around it. IRC channel and community are very helpful.

  • get_all_devices support
  • SCSI/ATA support
  • NVMe support (may not currently be possible given the state of the Haiku driver)

Help to test this tool in HBA/RAID

I can help to test this tool with HBA/RAID controllers. I think this code may support disk thourgh HBA and JBOD Mode through RAID.

I will attach the test result in future.

Got error when connect a "USB to SATA" device

I have a "USB to SATA" device(and connect a SATA SSD to it) in system, and install CentOS 8.4 to it.

When I use it as follow:

from smartie.device import get_all_devices

for device in get_all_devices():
    print(device.path)
    print(device.model)
    print(device.serial)
    print(device.temperature)

Error output:

/dev/sda
Traceback (most recent call last):
  File "/root/my_test.py", line 6, in <module>
    print (device.model)
  File "/usr/local/lib/python3.9/site-packages/smartie/scsi/__init__.py", line 133, in model
    identity, sense = self.identify()
  File "/usr/local/lib/python3.9/site-packages/smartie/scsi/__init__.py", line 115, in identify
    sense = self.issue_command(Direction.FROM, command16, identity)
  File "/usr/local/lib/python3.9/site-packages/smartie/scsi/linux.py", line 67, in issue_command
    raise OSError(ctypes.get_errno())
OSError: 25

smartie cannot support SAS Disk

I test smartie with SAS disk, here is my disk info:

[root@localhost ~]# smartctl -a /dev/sdb
smartctl 7.1 2020-04-05 r5049 [x86_64-linux-4.18.0-305.3.1.el8.x86_64] (local build)
Copyright (C) 2002-19, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Vendor:               XXXXXXX ( I hide information here)
Product:              MZILT1T9HBJRV3
Revision:             CN32
Compliance:           SPC-4
User Capacity:        1,920,383,410,176 bytes [1.92 TB]
Logical block size:   512 bytes
Physical block size:  4096 bytes
LU is resource provisioned, LBPRZ=1
Rotation Rate:        Solid State Device
Form Factor:          2.5 inches
Logical Unit id:      XXXXXXX ( I hide information here)
Serial number:        XXXXXXX ( I hide information here)
Device type:          disk
Transport protocol:   SAS (SPL-3)
Local Time is:        Fri Sep  1 07:52:12 2023 EDT
SMART support is:     Available - device has SMART capability.
SMART support is:     Enabled
Temperature Warning:  Enabled

=== START OF READ SMART DATA SECTION ===
SMART Health Status: OK

Percentage used endurance indicator: 0%
Current Drive Temperature:     31 C
Drive Trip Temperature:        65 C

Manufactured in week 41 of year 2019
Accumulated start-stop cycles:  145
Specified load-unload count over device lifetime:  0
Accumulated load-unload cycles:  0
Elements in grown defect list: 0

Error counter log:
           Errors Corrected by           Total   Correction     Gigabytes    Total
               ECC          rereads/    errors   algorithm      processed    uncorrected
           fast | delayed   rewrites  corrected  invocations   [10^9 bytes]  errors
read:          0        0         0         0          0      44609.083           0
write:         0        0         0         0          0      80920.541           0
verify:        0        0         0         0          0          0.109           0

Non-medium error count:      828

SMART Self-test log
Num  Test              Status                 segment  LifeTime  LBA_first_err [SK ASC ASQ]
     Description                              number   (hours)
# 1  Background short  Completed                   -     819                 - [-   -    -]

Long (extended) Self-test duration: 3600 seconds [60.0 minutes]

Error occurs when use smartie details:

[root@localhost ~]# smartie details /dev/sdb
Traceback (most recent call last):
  File "/usr/local/lib/python3.11/site-packages/smartie/scsi/__init__.py", line 115, in identify
    sense = self.issue_command(Direction.FROM, command16, identity)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/smartie/scsi/linux.py", line 69, in issue_command
    return self.parse_sense(raw_sense.raw)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/smartie/scsi/__init__.py", line 53, in parse_sense
    raise SenseError(sense.sense_key, sense=sense)
smartie.errors.SenseError: <SenseError(error_code=0x05, err='Illegal Request')>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/bin/smartie", line 8, in <module>
    sys.exit(cli())
             ^^^^^
  File "/usr/local/lib/python3.11/site-packages/click/core.py", line 1130, in __call__
    return self.main(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/click/core.py", line 1055, in main
    rv = self.invoke(ctx)
         ^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/click/core.py", line 1657, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/click/core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/click/core.py", line 760, in invoke
    return __callback(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/smartie/cli.py", line 130, in details_command
    details_table.add_row("Model Number", device.model)
                                          ^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/smartie/scsi/__init__.py", line 133, in model
    identity, sense = self.identify()
                      ^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/smartie/scsi/__init__.py", line 124, in identify
    sense = self.issue_command(Direction.FROM, command16, identity)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/smartie/scsi/linux.py", line 69, in issue_command
    return self.parse_sense(raw_sense.raw)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/smartie/scsi/__init__.py", line 53, in parse_sense
    raise SenseError(sense.sense_key, sense=sense)
smartie.errors.SenseError: <SenseError(error_code=0x05, err='Illegal Request')>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.