pySMART

Copyright (C) 2014 Marc Herndon

pySMART is a simple Python wrapper for the smartctl component of smartmontools. It works under Linux and Windows, as long as smartctl is on the system path. Running with administrative (root) privilege is strongly recommended, as smartctl cannot accurately detect all device types or parse all SMART information without full permissions.

With only a device's name (ie: /dev/sda, pd0), the API will create a Device object, populated with all relevant information about that device. The documented API can then be used to query this object for information, initiate device self-tests, and perform other functions.

Usage

The most common way to use pySMART is to create a logical representation of the physical storage device that you would like to work with, as shown:

#!bash
>>> from pySMART import Device
>>> sda = Device('/dev/sda')
>>> sda
<SATA device on /dev/sda mod:WDC WD5000AAKS-60Z1A0 sn:WD-WCAWFxxxxxxx>

Device class members can be accessed directly, and a number of helper methods are provided to retrieve information in bulk. Some examples are shown below:

#!bash
>>> sda.assessment  # Query the SMART self-assessment
'PASS'
>>> sda.attributes[9]  # Query a single SMART attribute
<SMART Attribute 'Power_On_Hours' 068/000 raw:23644>
>>> sda.all_attributes()  # Print the entire SMART attribute table
ID# ATTRIBUTE_NAME          CUR WST THR TYPE     UPDATED WHEN_FAIL    RAW
  1 Raw_Read_Error_Rate     200 200 051 Pre-fail Always  -           0
  3 Spin_Up_Time            141 140 021 Pre-fail Always  -           3908
  4 Start_Stop_Count        098 098 000 Old_age  Always  -           2690
  5 Reallocated_Sector_Ct   200 200 140 Pre-fail Always  -           0
    ... # Edited for brevity
199 UDMA_CRC_Error_Count    200 200 000 Old_age  Always  -           0
200 Multi_Zone_Error_Rate   200 200 000 Old_age  Offline -           0
>>> sda.tests[0]  # Query the most recent self-test result
<SMART Self-test [Short offline|Completed without error] hrs:23734 lba:->
>>> sda.all_selftests()  # Print the entire self-test log
ID Test_Description Status                        Left Hours  1st_Error@lba
 1 Short offline    Completed without error       00%  23734  -
 2 Short offline    Completed without error       00%  23734  -
   ... # Edited for brevity
 7 Short offline    Completed without error       00%  23726  -
 8 Short offline    Completed without error       00%  1      -

Alternatively, the package provides a DeviceList class. When instantiated, this will auto-detect all local storage devices and create a list containing one Device object for each detected storage device.

#!bash
>>> from pySMART import DeviceList
>>> devlist = DeviceList()
>>> devlist
<DeviceList contents:
<SAT device on /dev/sdb mod:WDC WD20EADS-00R6B0 sn:WD-WCAVYxxxxxxx>
<SAT device on /dev/sdc mod:WDC WD20EADS-00S2B0 sn:WD-WCAVYxxxxxxx>
<CSMI device on /dev/csmi0,0 mod:WDC WD5000AAKS-60Z1A0 sn:WD-WCAWFxxxxxxx>
>
>>> devlist.devices[0].attributes[5]  # Access Device data as above
<SMART Attribute 'Reallocated_Sector_Ct' 173/140 raw:214>

In the above cases if a new DeviceList is empty or a specific Device reports an "UNKNOWN INTERFACE", you are likely running without administrative privileges. On POSIX systems, you can request smartctl is run as a superuser by setting the sudo attribute of the global SMARTCTL object to True. Note this may cause you to be prompted for a password.

#!bash
>>> from pySMART import DeviceList
>>> from pySMART import Device
>>> sda = Device('/dev/sda')
>>> sda
<UNKNOWN INTERFACE device on /dev/sda mod:None sn:None>
>>> devlist = DeviceList()
>>> devlist
<DeviceList contents:
>
>>> from pySMART import SMARTCTL
>>> SMARTCTL.sudo = True
>>> sda = Device('/dev/sda')
>>> sda
[sudo] password for user:
<SAT device on /dev/sda mod:ST10000DM0004-1ZC101 sn:ZA20VNPT>
>>> devlist = DeviceList()
>>> devlist
<DeviceList contents:
<NVME device on /dev/nvme0 mod:Sabrent Rocket 4.0 1TB sn:03850709185D88300410>
<NVME device on /dev/nvme1 mod:Samsung SSD 970 EVO Plus 2TB sn:S59CNM0RB05028D>
<NVME device on /dev/nvme2 mod:Samsung SSD 970 EVO Plus 2TB sn:S59CNM0RB05113H>
<SAT device on /dev/sda mod:ST10000DM0004-1ZC101 sn:ZA20VNPT>
<SAT device on /dev/sdb mod:ST10000DM0004-1ZC101 sn:ZA22W366>
<SAT device on /dev/sdc mod:ST10000DM0004-1ZC101 sn:ZA22SPLG>
<SAT device on /dev/sdd mod:ST10000DM0004-1ZC101 sn:ZA2215HL>
>

In general, it is recommended to run the base script with enough privileges to execute smartctl, but this is not possible in all cases, so this workaround is provided as a convenience. However, note that using sudo inside other non-terminal projects may cause dev-bugs/issues.

Using the pySMART wrapper, Python applications be be rapidly developed to take advantage of the powerful features of smartmontools.

Acknowledgements

I would like to thank the entire team behind smartmontools for creating and maintaining such a fantastic product.

In particular I want to thank Christian Franke, who maintains the Windows port of the software. For several years I have written Windows batch files that rely on smartctl.exe to automate evaluation and testing of large pools of storage devices under Windows. Without his work, my job would have been significantly more miserable. :)

Having recently migrated my development from Batch to Python for Linux portability, I thought a simple wrapper for smartctl would save time in the development of future automated test tools.

  1# Copyright (C) 2014 Marc Herndon
  2#
  3# This program is free software; you can redistribute it and/or
  4# modify it under the terms of the GNU General Public License,
  5# version 2, as published by the Free Software Foundation.
  6#
  7# This program is distributed in the hope that it will be useful,
  8# but WITHOUT ANY WARRANTY; without even the implied warranty of
  9# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 10# GNU General Public License for more details.
 11#
 12# You should have received a copy of the GNU General Public License
 13# along with this program; if not, write to the Free Software
 14# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 15# MA  02110-1301, USA.
 16#
 17################################################################
 18"""
 19Copyright (C) 2014 Marc Herndon
 20
 21pySMART is a simple Python wrapper for the `smartctl` component of
 22`smartmontools`. It works under Linux and Windows, as long as smartctl is on
 23the system path. Running with administrative (root) privilege is strongly
 24recommended, as smartctl cannot accurately detect all device types or parse
 25all SMART information without full permissions.
 26
 27With only a device's name (ie: /dev/sda, pd0), the API will create a
 28`Device` object, populated with all relevant information about
 29that device. The documented API can then be used to query this object for
 30information, initiate device self-tests, and perform other functions.
 31
 32Usage
 33-----
 34The most common way to use pySMART is to create a logical representation of the
 35physical storage device that you would like to work with, as shown:
 36
 37    #!bash
 38    >>> from pySMART import Device
 39    >>> sda = Device('/dev/sda')
 40    >>> sda
 41    <SATA device on /dev/sda mod:WDC WD5000AAKS-60Z1A0 sn:WD-WCAWFxxxxxxx>
 42
 43`Device` class members can be accessed directly, and a number of helper methods
 44are provided to retrieve information in bulk.  Some examples are shown below:
 45
 46    #!bash
 47    >>> sda.assessment  # Query the SMART self-assessment
 48    'PASS'
 49    >>> sda.attributes[9]  # Query a single SMART attribute
 50    <SMART Attribute 'Power_On_Hours' 068/000 raw:23644>
 51    >>> sda.all_attributes()  # Print the entire SMART attribute table
 52    ID# ATTRIBUTE_NAME          CUR WST THR TYPE     UPDATED WHEN_FAIL    RAW
 53      1 Raw_Read_Error_Rate     200 200 051 Pre-fail Always  -           0
 54      3 Spin_Up_Time            141 140 021 Pre-fail Always  -           3908
 55      4 Start_Stop_Count        098 098 000 Old_age  Always  -           2690
 56      5 Reallocated_Sector_Ct   200 200 140 Pre-fail Always  -           0
 57        ... # Edited for brevity
 58    199 UDMA_CRC_Error_Count    200 200 000 Old_age  Always  -           0
 59    200 Multi_Zone_Error_Rate   200 200 000 Old_age  Offline -           0
 60    >>> sda.tests[0]  # Query the most recent self-test result
 61    <SMART Self-test [Short offline|Completed without error] hrs:23734 lba:->
 62    >>> sda.all_selftests()  # Print the entire self-test log
 63    ID Test_Description Status                        Left Hours  1st_Error@lba
 64     1 Short offline    Completed without error       00%  23734  -
 65     2 Short offline    Completed without error       00%  23734  -
 66       ... # Edited for brevity
 67     7 Short offline    Completed without error       00%  23726  -
 68     8 Short offline    Completed without error       00%  1      -
 69
 70Alternatively, the package provides a `DeviceList` class. When instantiated,
 71this will auto-detect all local storage devices and create a list containing
 72one `Device` object for each detected storage device.
 73
 74    #!bash
 75    >>> from pySMART import DeviceList
 76    >>> devlist = DeviceList()
 77    >>> devlist
 78    <DeviceList contents:
 79    <SAT device on /dev/sdb mod:WDC WD20EADS-00R6B0 sn:WD-WCAVYxxxxxxx>
 80    <SAT device on /dev/sdc mod:WDC WD20EADS-00S2B0 sn:WD-WCAVYxxxxxxx>
 81    <CSMI device on /dev/csmi0,0 mod:WDC WD5000AAKS-60Z1A0 sn:WD-WCAWFxxxxxxx>
 82    >
 83    >>> devlist.devices[0].attributes[5]  # Access Device data as above
 84    <SMART Attribute 'Reallocated_Sector_Ct' 173/140 raw:214>
 85
 86In the above cases if a new DeviceList is empty or a specific Device reports an
 87"UNKNOWN INTERFACE", you are likely running without administrative privileges.
 88On POSIX systems, you can request smartctl is run as a superuser by setting the
 89sudo attribute of the global SMARTCTL object to True. Note this may cause you
 90to be prompted for a password.
 91
 92    #!bash
 93    >>> from pySMART import DeviceList
 94    >>> from pySMART import Device
 95    >>> sda = Device('/dev/sda')
 96    >>> sda
 97    <UNKNOWN INTERFACE device on /dev/sda mod:None sn:None>
 98    >>> devlist = DeviceList()
 99    >>> devlist
100    <DeviceList contents:
101    >
102    >>> from pySMART import SMARTCTL
103    >>> SMARTCTL.sudo = True
104    >>> sda = Device('/dev/sda')
105    >>> sda
106    [sudo] password for user:
107    <SAT device on /dev/sda mod:ST10000DM0004-1ZC101 sn:ZA20VNPT>
108    >>> devlist = DeviceList()
109    >>> devlist
110    <DeviceList contents:
111    <NVME device on /dev/nvme0 mod:Sabrent Rocket 4.0 1TB sn:03850709185D88300410>
112    <NVME device on /dev/nvme1 mod:Samsung SSD 970 EVO Plus 2TB sn:S59CNM0RB05028D>
113    <NVME device on /dev/nvme2 mod:Samsung SSD 970 EVO Plus 2TB sn:S59CNM0RB05113H>
114    <SAT device on /dev/sda mod:ST10000DM0004-1ZC101 sn:ZA20VNPT>
115    <SAT device on /dev/sdb mod:ST10000DM0004-1ZC101 sn:ZA22W366>
116    <SAT device on /dev/sdc mod:ST10000DM0004-1ZC101 sn:ZA22SPLG>
117    <SAT device on /dev/sdd mod:ST10000DM0004-1ZC101 sn:ZA2215HL>
118    >
119
120In general, it is recommended to run the base script with enough privileges to
121execute smartctl, but this is not possible in all cases, so this workaround is
122provided as a convenience. However, note that using sudo inside other
123non-terminal projects may cause dev-bugs/issues.
124
125
126Using the pySMART wrapper, Python applications be be rapidly developed to take
127advantage of the powerful features of smartmontools.
128
129Acknowledgements
130----------------
131I would like to thank the entire team behind smartmontools for creating and
132maintaining such a fantastic product.
133
134In particular I want to thank Christian Franke, who maintains the Windows port
135of the software.  For several years I have written Windows batch files that
136rely on smartctl.exe to automate evaluation and testing of large pools of
137storage devices under Windows.  Without his work, my job would have been
138significantly more miserable. :)
139
140Having recently migrated my development from Batch to Python for Linux
141portability, I thought a simple wrapper for smartctl would save time in the
142development of future automated test tools.
143"""
144# autopep8: off
145from .testentry import TestEntry
146from .attribute import Attribute
147from . import utils
148utils.configure_trace_logging()
149from .smartctl import SMARTCTL
150from .device_list import DeviceList
151from .device import Device, smart_health_assement
152from .version import __version__,__version_tuple__
153# autopep8: on
154
155
156__all__ = [
157    '__version__', '__version_tuple__',
158    'TestEntry', 'Attribute', 'utils', 'SMARTCTL', 'DeviceList', 'Device',
159    'smart_health_assement'
160]
__version__ = '1.2.5.dev23'
__version_tuple__ = (1, 2, 5, 'dev23')
class TestEntry:
 27class TestEntry(object):
 28    """
 29    Contains all of the information associated with a single SMART Self-test
 30    log entry. This data is intended to exactly mirror that obtained through
 31    smartctl.
 32    """
 33
 34    def __init__(self, format, num: Optional[int], test_type, status, hours, lba,
 35                 remain=None,
 36                 segment=None,
 37                 sense=None,
 38                 asc=None,
 39                 ascq=None,
 40                 nsid=None,
 41                 sct=None,
 42                 code=None):
 43
 44        self._format = format
 45        """
 46        **(str):** Indicates whether this entry was taken from an 'ata' or
 47        'scsi' self-test log. Used to display the content properly.
 48        """
 49        self.num: Optional[int] = num
 50        """
 51        **(int):** Entry's position in the log from 1 (most recent) to 21
 52        (least recent).  ATA logs save the last 21 entries while SCSI logs
 53        only save the last 20.
 54        """
 55        self.type = test_type
 56        """
 57        **(str):** Type of test run.  Generally short, long (extended), or
 58        conveyance, plus offline (background) or captive (foreground).
 59        """
 60        self.status = status
 61        """
 62        **(str):** Self-test's status message, for example 'Completed without
 63        error' or 'Completed: read failure'.
 64        """
 65        self.hours = hours
 66        """
 67        **(str):** The device's power-on hours at the time the self-test
 68        was initiated.
 69        """
 70        self.LBA = lba
 71        """
 72        **(str):** Indicates the first LBA at which an error was encountered
 73        during this self-test. Presented as a decimal value for ATA/SATA
 74        devices and in hexadecimal notation for SAS/SCSI devices.
 75        """
 76        self.remain = remain
 77        """
 78        **(str):** Percentage value indicating how much of the self-test is
 79        left to perform. '00%' indicates a complete test, while any other
 80        value could indicate a test in progress or one that failed prior to
 81        completion. Only reported by ATA devices.
 82        """
 83        self.segment = segment
 84        """
 85        **(str):** A manufacturer-specific self-test segment number reported
 86        by SCSI devices on self-test failure. Set to '-' otherwise.
 87        """
 88        self.sense = sense
 89        """
 90        **(str):** SCSI sense key reported on self-test failure. Set to '-'
 91        otherwise.
 92        """
 93        self.ASC = asc
 94        """
 95        **(str):** SCSI 'Additonal Sense Code' reported on self-test failure.
 96        Set to '-' otherwise.
 97        """
 98        self.ASCQ = ascq
 99        """
100        **(str):** SCSI 'Additonal Sense Code Quaifier' reported on self-test
101        failure. Set to '-' otherwise.
102        """
103        self.nsid = nsid
104        """
105        **(str):** NVMe 'Name Space Identifier' reported on self-test failure.
106        Set to '-' if no namespace is defined.
107        """
108        self.sct = sct
109        """
110        **(str):** NVMe 'Status Code Type' reported on self-test failure.
111        Set to '-' if undefined.
112        """
113        self.code = code
114        """
115        **(str):** NVMe 'Status Code' reported on self-test failure.
116        Set to '-' if undefined.
117        """
118
119    def __getstate__(self):
120        return {
121            'num': self.num,
122            'type': self.type,
123            'status': self.status,
124            'hours': self.hours,
125            'lba': self.LBA,
126            'remain': self.remain,
127            'segment': self.segment,
128            'sense': self.sense,
129            'asc': self.ASC,
130            'ascq': self.ASCQ,
131            'nsid': self.nsid,
132            'sct': self.sct,
133            'code': self.code
134        }
135
136    def __repr__(self):
137        """Define a basic representation of the class object."""
138        return "<SMART Self-test [%s|%s] hrs:%s LBA:%s>" % (
139            self.type, self.status, self.hours, self.LBA)
140
141    def __str__(self):
142        """
143        Define a formatted string representation of the object's content.
144        Looks nearly identical to the output of smartctl, without overflowing
145        80-character lines.
146        """
147        if self._format == 'ata':
148            return "{0:>2} {1:17}{2:30}{3:5}{4:7}{5:17}".format(
149                self.num, self.type, self.status, self.remain, self.hours,
150                self.LBA)
151        elif self._format == 'scsi':
152            # 'Segment' could not be fit on the 80-char line. It's of limited
153            # utility anyway due to it's manufacturer-proprietary nature...
154            return ("{0:>2} {1:17}{2:23}{3:7}{4:14}[{5:4}{6:5}{7:4}]".format(
155                self.num,
156                self.type,
157                self.status,
158                self.hours,
159                self.LBA,
160                self.sense,
161                self.ASC,
162                self.ASCQ
163            ))
164        elif self._format == 'nvme':
165            ## NVME FORMAT ##
166            # Example smartctl output
167            # Self-test Log (NVMe Log 0x06)
168            # Self-test status: Extended self-test in progress (28% completed)
169            # Num  Test_Description  Status                       Power_on_Hours  Failing_LBA  NSID SCT Code
170            #  0   Extended          Completed without error                3441            -     -   -    -
171            return ("{0:^4} {1:<18}{2:<29}{3:>14}{4:>13}{5:>6}{6:>4}{7:>5}".format(
172                self.num,
173                self.type,
174                self.status,
175                self.hours,
176                self.LBA if self.LBA is not None else '-',
177                self.nsid if self.LBA is not None else '-',
178                self.sct if self.LBA is not None else '-',
179                self.code if self.LBA is not None else '-'
180            ))
181        else:
182            return "Unknown test format: %s" % self._format

Contains all of the information associated with a single SMART Self-test log entry. This data is intended to exactly mirror that obtained through smartctl.

TestEntry( format, num: Optional[int], test_type, status, hours, lba, remain=None, segment=None, sense=None, asc=None, ascq=None, nsid=None, sct=None, code=None)
 34    def __init__(self, format, num: Optional[int], test_type, status, hours, lba,
 35                 remain=None,
 36                 segment=None,
 37                 sense=None,
 38                 asc=None,
 39                 ascq=None,
 40                 nsid=None,
 41                 sct=None,
 42                 code=None):
 43
 44        self._format = format
 45        """
 46        **(str):** Indicates whether this entry was taken from an 'ata' or
 47        'scsi' self-test log. Used to display the content properly.
 48        """
 49        self.num: Optional[int] = num
 50        """
 51        **(int):** Entry's position in the log from 1 (most recent) to 21
 52        (least recent).  ATA logs save the last 21 entries while SCSI logs
 53        only save the last 20.
 54        """
 55        self.type = test_type
 56        """
 57        **(str):** Type of test run.  Generally short, long (extended), or
 58        conveyance, plus offline (background) or captive (foreground).
 59        """
 60        self.status = status
 61        """
 62        **(str):** Self-test's status message, for example 'Completed without
 63        error' or 'Completed: read failure'.
 64        """
 65        self.hours = hours
 66        """
 67        **(str):** The device's power-on hours at the time the self-test
 68        was initiated.
 69        """
 70        self.LBA = lba
 71        """
 72        **(str):** Indicates the first LBA at which an error was encountered
 73        during this self-test. Presented as a decimal value for ATA/SATA
 74        devices and in hexadecimal notation for SAS/SCSI devices.
 75        """
 76        self.remain = remain
 77        """
 78        **(str):** Percentage value indicating how much of the self-test is
 79        left to perform. '00%' indicates a complete test, while any other
 80        value could indicate a test in progress or one that failed prior to
 81        completion. Only reported by ATA devices.
 82        """
 83        self.segment = segment
 84        """
 85        **(str):** A manufacturer-specific self-test segment number reported
 86        by SCSI devices on self-test failure. Set to '-' otherwise.
 87        """
 88        self.sense = sense
 89        """
 90        **(str):** SCSI sense key reported on self-test failure. Set to '-'
 91        otherwise.
 92        """
 93        self.ASC = asc
 94        """
 95        **(str):** SCSI 'Additonal Sense Code' reported on self-test failure.
 96        Set to '-' otherwise.
 97        """
 98        self.ASCQ = ascq
 99        """
100        **(str):** SCSI 'Additonal Sense Code Quaifier' reported on self-test
101        failure. Set to '-' otherwise.
102        """
103        self.nsid = nsid
104        """
105        **(str):** NVMe 'Name Space Identifier' reported on self-test failure.
106        Set to '-' if no namespace is defined.
107        """
108        self.sct = sct
109        """
110        **(str):** NVMe 'Status Code Type' reported on self-test failure.
111        Set to '-' if undefined.
112        """
113        self.code = code
114        """
115        **(str):** NVMe 'Status Code' reported on self-test failure.
116        Set to '-' if undefined.
117        """
num: Optional[int]

(int): Entry's position in the log from 1 (most recent) to 21 (least recent). ATA logs save the last 21 entries while SCSI logs only save the last 20.

type

(str): Type of test run. Generally short, long (extended), or conveyance, plus offline (background) or captive (foreground).

status

(str): Self-test's status message, for example 'Completed without error' or 'Completed: read failure'.

hours

(str): The device's power-on hours at the time the self-test was initiated.

LBA

(str): Indicates the first LBA at which an error was encountered during this self-test. Presented as a decimal value for ATA/SATA devices and in hexadecimal notation for SAS/SCSI devices.

remain

(str): Percentage value indicating how much of the self-test is left to perform. '00%' indicates a complete test, while any other value could indicate a test in progress or one that failed prior to completion. Only reported by ATA devices.

segment

(str): A manufacturer-specific self-test segment number reported by SCSI devices on self-test failure. Set to '-' otherwise.

sense

(str): SCSI sense key reported on self-test failure. Set to '-' otherwise.

ASC

(str): SCSI 'Additonal Sense Code' reported on self-test failure. Set to '-' otherwise.

ASCQ

(str): SCSI 'Additonal Sense Code Quaifier' reported on self-test failure. Set to '-' otherwise.

nsid

(str): NVMe 'Name Space Identifier' reported on self-test failure. Set to '-' if no namespace is defined.

sct

(str): NVMe 'Status Code Type' reported on self-test failure. Set to '-' if undefined.

code

(str): NVMe 'Status Code' reported on self-test failure. Set to '-' if undefined.

class Attribute:
 28class Attribute(object):
 29    """
 30    Contains all of the information associated with a single SMART attribute
 31    in a `Device`'s SMART table. This data is intended to exactly mirror that
 32    obtained through smartctl.
 33    """
 34
 35    def __init__(self, num: int, name, flags: int, value, worst, thresh, attr_type, updated, when_failed, raw):
 36        self.num: int = num
 37        """**(int):** Attribute's ID as a decimal value (1-255)."""
 38        self.name: str = name
 39        """
 40        **(str):** Attribute's name, as reported by smartmontools' drive.db.
 41        """
 42        self.flags: int = flags
 43        """**(int):** Attribute flags as a bit value (ie: 0x0032)."""
 44        self._value: str = value
 45        """**(str):** Attribute's current normalized value."""
 46        self._worst: str = worst
 47        """**(str):** Worst recorded normalized value for this attribute."""
 48        self._thresh: str = thresh
 49        """**(str):** Attribute's failure threshold."""
 50        self.type: str = attr_type
 51        """**(str):** Attribute's type, generally 'pre-fail' or 'old-age'."""
 52        self.updated: str = updated
 53        """
 54        **(str):** When is this attribute updated? Generally 'Always' or
 55        'Offline'
 56        """
 57        self.when_failed: str = when_failed
 58        """
 59        **(str):** When did this attribute cross below
 60        `pySMART.attribute.Attribute.thresh`? Reads '-' when not failed.
 61        Generally either 'FAILING_NOW' or 'In_the_Past' otherwise.
 62        """
 63        self.raw = raw
 64        """**(str):** Attribute's current raw (non-normalized) value."""
 65
 66    @property
 67    def value_str(self) -> str:
 68        """Gets the attribute value
 69
 70        Returns:
 71            str: The attribute value in string format
 72        """
 73        return self._value
 74
 75    @property
 76    def value_int(self) -> int:
 77        """Gets the attribute value
 78
 79        Returns:
 80            int: The attribute value in integer format.
 81        """
 82        return int(self._value)
 83
 84    @property
 85    def value(self) -> str:
 86        """Gets the attribue value
 87
 88        Returns:
 89            str: The attribute value in string format
 90        """
 91        return self.value_str
 92
 93    @property
 94    def worst(self) -> int:
 95        """Gets the worst value
 96
 97        Returns:
 98            int: The attribute worst field in integer format
 99        """
100        return int(self._worst)
101
102    @property
103    def thresh(self) -> Optional[int]:
104        """Gets the threshold value
105
106        Returns:
107            int: The attribute threshold field in integer format
108        """
109        return None if self._thresh == '---' else int(self._thresh)
110
111    @property
112    def raw_int(self) -> Optional[int]:
113        """Gets the raw value converted to int
114        NOTE: Some values may not be correctly converted!
115
116        Returns:
117            int: The attribute raw-value field in integer format.
118            None: In case the raw string failed to be parsed
119        """
120        try:
121            return int(re.search(r'\d+', self.raw).group())
122        except:
123            return None
124
125    def __repr__(self):
126        """Define a basic representation of the class object."""
127        return "<SMART Attribute %r %s/%s raw:%s>" % (
128            self.name, self.value, self.thresh, self.raw)
129
130    def __str__(self):
131        """
132        Define a formatted string representation of the object's content.
133        In the interest of not overflowing 80-character lines this does not
134        print the value of `pySMART.attribute.Attribute.flags_hex`.
135        """
136        return "{0:>3} {1:23}{2:>4}{3:>4}{4:>4} {5:9}{6:8}{7:12}{8}".format(
137            self.num,
138            self.name,
139            self.value,
140            self.worst,
141            self.thresh,
142            self.type,
143            self.updated,
144            self.when_failed,
145            self.raw
146        )
147
148    def __getstate__(self):
149        return {
150            'num': self.num,
151            'flags': self.flags,
152            'raw': self.raw,
153            'value': self.value,
154            'worst': self.worst,
155            'threshold': self.thresh,
156            'type': self.type,
157            'updated': self.updated,
158            'when_failed': self.when_failed,
159        }

Contains all of the information associated with a single SMART attribute in a Device's SMART table. This data is intended to exactly mirror that obtained through smartctl.

Attribute( num: int, name, flags: int, value, worst, thresh, attr_type, updated, when_failed, raw)
35    def __init__(self, num: int, name, flags: int, value, worst, thresh, attr_type, updated, when_failed, raw):
36        self.num: int = num
37        """**(int):** Attribute's ID as a decimal value (1-255)."""
38        self.name: str = name
39        """
40        **(str):** Attribute's name, as reported by smartmontools' drive.db.
41        """
42        self.flags: int = flags
43        """**(int):** Attribute flags as a bit value (ie: 0x0032)."""
44        self._value: str = value
45        """**(str):** Attribute's current normalized value."""
46        self._worst: str = worst
47        """**(str):** Worst recorded normalized value for this attribute."""
48        self._thresh: str = thresh
49        """**(str):** Attribute's failure threshold."""
50        self.type: str = attr_type
51        """**(str):** Attribute's type, generally 'pre-fail' or 'old-age'."""
52        self.updated: str = updated
53        """
54        **(str):** When is this attribute updated? Generally 'Always' or
55        'Offline'
56        """
57        self.when_failed: str = when_failed
58        """
59        **(str):** When did this attribute cross below
60        `pySMART.attribute.Attribute.thresh`? Reads '-' when not failed.
61        Generally either 'FAILING_NOW' or 'In_the_Past' otherwise.
62        """
63        self.raw = raw
64        """**(str):** Attribute's current raw (non-normalized) value."""
num: int

(int): Attribute's ID as a decimal value (1-255).

name: str

(str): Attribute's name, as reported by smartmontools' drive.db.

flags: int

(int): Attribute flags as a bit value (ie: 0x0032).

type: str

(str): Attribute's type, generally 'pre-fail' or 'old-age'.

updated: str

(str): When is this attribute updated? Generally 'Always' or 'Offline'

when_failed: str

(str): When did this attribute cross below pySMART.Attribute.thresh? Reads '-' when not failed. Generally either 'FAILING_NOW' or 'In_the_Past' otherwise.

raw

(str): Attribute's current raw (non-normalized) value.

value_str: str

Gets the attribute value

Returns: str: The attribute value in string format

value_int: int

Gets the attribute value

Returns: int: The attribute value in integer format.

value: str

Gets the attribue value

Returns: str: The attribute value in string format

worst: int

Gets the worst value

Returns: int: The attribute worst field in integer format

thresh: Optional[int]

Gets the threshold value

Returns: int: The attribute threshold field in integer format

raw_int: Optional[int]

Gets the raw value converted to int NOTE: Some values may not be correctly converted!

Returns: int: The attribute raw-value field in integer format. None: In case the raw string failed to be parsed

SMARTCTL = <pySMART.smartctl.Smartctl object>
class DeviceList:
 37class DeviceList(object):
 38    """
 39    Represents a list of all the storage devices connected to this computer.
 40    """
 41
 42    def __init__(self, init: bool = True, smartctl=SMARTCTL, catch_errors: bool = False):
 43        """Instantiates and optionally initializes the `DeviceList`.
 44
 45        Args:
 46            init (bool, optional): By default, `pySMART.device_list.DeviceList.devices`
 47                is populated with `Device` objects during instantiation. Setting init
 48                to False will skip initialization and create an empty
 49                `pySMART.device_list.DeviceList` object instead. Defaults to True.
 50            smartctl ([type], optional): This stablish the smartctl wrapper.
 51                Defaults the global `SMARTCTL` object and should be only
 52                overwritten on tests.
 53            catch_errors (bool, optional): If True, individual device-parsing errors will be caught
 54        """
 55
 56        self.devices: List[Device] = []
 57        """
 58        **(list of `Device`):** Contains all storage devices detected during
 59        instantiation, as `Device` objects.
 60        """
 61        self.smartctl: Smartctl = smartctl
 62        """The smartctl wrapper
 63        """
 64        if init:
 65            self.initialize(catch_errors)
 66
 67    def __repr__(self):
 68        """Define a basic representation of the class object."""
 69        rep = "<DeviceList contents:\n"
 70        for device in self.devices:
 71            rep += str(device) + '\n'
 72        return rep + '>'
 73        # return "<DeviceList contents:%r>" % (self.devices)
 74
 75    def _cleanup(self):
 76        """
 77        Removes duplicate ATA devices that correspond to an existing CSMI
 78        device. Also removes any device with no capacity value, as this
 79        indicates removable storage, ie: CD/DVD-ROM, ZIP, etc.
 80        """
 81        # We can't operate directly on the list while we're iterating
 82        # over it, so we collect indeces to delete and remove them later
 83        to_delete = []
 84        # Enumerate the list to get tuples containing indeces and values
 85        for index, device in enumerate(self.devices):
 86            if device.interface == 'csmi':
 87                for otherindex, otherdevice in enumerate(self.devices):
 88                    if (otherdevice.interface == 'ata' or
 89                            otherdevice.interface == 'sata'):
 90                        if device.serial == otherdevice.serial:
 91                            to_delete.append(otherindex)
 92                            device._sd_name = otherdevice.name
 93            if device.capacity is None and index not in to_delete:
 94                to_delete.append(index)
 95        # Recreate the self.devices list without the marked indeces
 96        self.devices[:] = [v for i, v in enumerate(self.devices)
 97                           if i not in to_delete]
 98
 99    def initialize(self, catch_errors: bool = False):
100        """
101        Scans system busses for attached devices and add them to the
102        `DeviceList` as `Device` objects.
103        If device list is already populated, it will be cleared first.
104
105        Args:
106            catch_errors (bool, optional): If True, individual device-parsing errors will be caught
107        """
108
109        # Clear the list if it's already populated
110        if len(self.devices):
111            self.devices = []
112
113        # Scan for devices
114        for line in self.smartctl.scan():
115            if not ('failed:' in line or line == ''):
116                groups = re.compile(
117                    r'^(\S+)\s+-d\s+(\S+)').match(line).groups()
118                name = groups[0]
119                interface = groups[1]
120
121                try:
122                    # Add the device to the list
123                    self.devices.append(
124                        Device(name, interface=interface, smartctl=self.smartctl))
125
126                except Exception as e:
127                    if catch_errors:
128                        # Print the exception
129                        import logging
130
131                        logging.exception(f"Error parsing device {name}")
132
133                    else:
134                        # Reraise the exception
135                        raise e
136
137        # Remove duplicates and unwanted devices (optical, etc.) from the list
138        self._cleanup()
139        # Sort the list alphabetically by device name
140        self.devices.sort(key=lambda device: device.name)
141
142    def __getitem__(self, index: int) -> Device:
143        """Returns an element from self.devices
144
145        Args:
146            index (int): An index of self.devices
147
148        Returns:
149            Device: Returns a Device that is located on the asked index
150        """
151        return self.devices[index]

Represents a list of all the storage devices connected to this computer.

DeviceList( init: bool = True, smartctl=<pySMART.smartctl.Smartctl object>, catch_errors: bool = False)
42    def __init__(self, init: bool = True, smartctl=SMARTCTL, catch_errors: bool = False):
43        """Instantiates and optionally initializes the `DeviceList`.
44
45        Args:
46            init (bool, optional): By default, `pySMART.device_list.DeviceList.devices`
47                is populated with `Device` objects during instantiation. Setting init
48                to False will skip initialization and create an empty
49                `pySMART.device_list.DeviceList` object instead. Defaults to True.
50            smartctl ([type], optional): This stablish the smartctl wrapper.
51                Defaults the global `SMARTCTL` object and should be only
52                overwritten on tests.
53            catch_errors (bool, optional): If True, individual device-parsing errors will be caught
54        """
55
56        self.devices: List[Device] = []
57        """
58        **(list of `Device`):** Contains all storage devices detected during
59        instantiation, as `Device` objects.
60        """
61        self.smartctl: Smartctl = smartctl
62        """The smartctl wrapper
63        """
64        if init:
65            self.initialize(catch_errors)

Instantiates and optionally initializes the DeviceList.

Args: init (bool, optional): By default, pySMART.DeviceList.devices is populated with Device objects during instantiation. Setting init to False will skip initialization and create an empty pySMART.DeviceList object instead. Defaults to True. smartctl ([type], optional): This stablish the smartctl wrapper. Defaults the global SMARTCTL object and should be only overwritten on tests. catch_errors (bool, optional): If True, individual device-parsing errors will be caught

devices: List[pySMART.Device]

(list of Device): Contains all storage devices detected during instantiation, as Device objects.

smartctl: pySMART.smartctl.Smartctl

The smartctl wrapper

def initialize(self, catch_errors: bool = False):
 99    def initialize(self, catch_errors: bool = False):
100        """
101        Scans system busses for attached devices and add them to the
102        `DeviceList` as `Device` objects.
103        If device list is already populated, it will be cleared first.
104
105        Args:
106            catch_errors (bool, optional): If True, individual device-parsing errors will be caught
107        """
108
109        # Clear the list if it's already populated
110        if len(self.devices):
111            self.devices = []
112
113        # Scan for devices
114        for line in self.smartctl.scan():
115            if not ('failed:' in line or line == ''):
116                groups = re.compile(
117                    r'^(\S+)\s+-d\s+(\S+)').match(line).groups()
118                name = groups[0]
119                interface = groups[1]
120
121                try:
122                    # Add the device to the list
123                    self.devices.append(
124                        Device(name, interface=interface, smartctl=self.smartctl))
125
126                except Exception as e:
127                    if catch_errors:
128                        # Print the exception
129                        import logging
130
131                        logging.exception(f"Error parsing device {name}")
132
133                    else:
134                        # Reraise the exception
135                        raise e
136
137        # Remove duplicates and unwanted devices (optical, etc.) from the list
138        self._cleanup()
139        # Sort the list alphabetically by device name
140        self.devices.sort(key=lambda device: device.name)

Scans system busses for attached devices and add them to the DeviceList as Device objects. If device list is already populated, it will be cleared first.

Args: catch_errors (bool, optional): If True, individual device-parsing errors will be caught

class Device:
  81class Device(object):
  82    """
  83    Represents any device attached to an internal storage interface, such as a
  84    hard drive or DVD-ROM, and detected by smartmontools. Includes eSATA
  85    (considered SATA) but excludes other external devices (USB, Firewire).
  86    """
  87
  88    def __init__(self, name: str, interface: Optional[str] = None, abridged: bool = False, smart_options: Union[str, List[str], None] = None, smartctl: Smartctl = SMARTCTL):
  89        """Instantiates and initializes the `pySMART.device.Device`."""
  90        if not (
  91                interface is None or
  92                smartctl_isvalid_type(interface.lower())
  93        ):
  94            raise ValueError(
  95                'Unknown interface: {0} specified for {1}'.format(interface, name))
  96        self.abridged = abridged or interface == 'UNKNOWN INTERFACE'
  97        if smart_options is not None:
  98            if isinstance(smart_options,  str):
  99                smart_options = smart_options.split(' ')
 100            smartctl.add_options(smart_options)
 101        self.smartctl = smartctl
 102        """
 103        """
 104        self.name: str = name.replace('/dev/', '').replace('nvd', 'nvme')
 105        """
 106        **(str):** Device's hardware ID, without the '/dev/' prefix.
 107        (ie: sda (Linux), pd0 (Windows))
 108        """
 109        self.family: Optional[str] = None
 110        """**(str):** Device's family (if any)."""
 111        self.model: Optional[str] = None
 112        """**(str):** Device's model number (if any)."""
 113        self.serial: Optional[str] = None
 114        """**(str):** Device's serial number (if any)."""
 115        self._vendor: Optional[str] = None
 116        """**(str):** Device's vendor (if any)."""
 117        self._interface: Optional[str] = None if interface == 'UNKNOWN INTERFACE' else interface
 118        """
 119        **(str):** Device's interface type. Must be one of:
 120            * **ATA** - Advanced Technology Attachment
 121            * **SATA** - Serial ATA
 122            * **SCSI** - Small Computer Systems Interface
 123            * **SAS** - Serial Attached SCSI
 124            * **SAT** - SCSI-to-ATA Translation (SATA device plugged into a
 125            SAS port)
 126            * **CSMI** - Common Storage Management Interface (Intel ICH /
 127            Matrix RAID)
 128        Generally this should not be specified to allow auto-detection to
 129        occur. Otherwise, this value overrides the auto-detected type and could
 130        produce unexpected or no data.
 131        """
 132        self._capacity: Optional[int] = None
 133        """**(str):** Device's user capacity as reported directly by smartctl (RAW)."""
 134        self._capacity_human: Optional[str] = None
 135        """**(str):** Device's user capacity (human readable) as reported directly by smartctl (RAW)."""
 136        self.firmware: Optional[str] = None
 137        """**(str):** Device's firmware version."""
 138        self.smart_capable: bool = 'nvme' in self.name
 139        """
 140        **(bool):** True if the device has SMART Support Available.
 141        False otherwise. This is useful for VMs amongst other things.
 142        """
 143        self.smart_enabled: bool = 'nvme' in self.name
 144        """
 145        **(bool):** True if the device supports SMART (or SCSI equivalent) and
 146        has the feature set enabled. False otherwise.
 147        """
 148        self.assessment: Optional[str] = None
 149        """
 150        **(str):** SMART health self-assessment as reported by the device.
 151        """
 152        self.messages: List[str] = []
 153        """
 154        **(list of str):** Contains any SMART warnings or other error messages
 155        reported by the device (ie: ascq codes).
 156        """
 157        self.is_ssd: bool = True if 'nvme' in self.name else False
 158        """
 159        **(bool):** True if this device is a Solid State Drive.
 160        False otherwise.
 161        """
 162        self.rotation_rate: Optional[int] = None
 163        """
 164        **(int):** The Roatation Rate of the Drive if it is not a SSD.
 165        The Metric is RPM.
 166        """
 167        self.attributes: List[Optional[Attribute]] = [None] * 256
 168        """
 169        **(list of `Attribute`):** Contains the complete SMART table
 170        information for this device, as provided by smartctl. Indexed by
 171        attribute #, values are set to 'None' for attributes not suported by
 172        this device.
 173        """
 174        self.test_capabilities = {
 175            'offline': False,  # SMART execute Offline immediate (ATA only)
 176            'short': 'nvme' not in self.name,  # SMART short Self-test
 177            'long': 'nvme' not in self.name,  # SMART long Self-test
 178            'conveyance': False,  # SMART Conveyance Self-Test (ATA only)
 179            'selective': False,  # SMART Selective Self-Test (ATA only)
 180        }
 181        # Note have not included 'offline' test for scsi as it runs in the foregorund
 182        # mode. While this may be beneficial to us in someways it is against the
 183        # general layout and pattern that the other tests issued using pySMART are
 184        # followed hence not doing it currently
 185        """
 186        **(dict): ** This dictionary contains key == 'Test Name' and
 187        value == 'True/False' of self-tests that this device is capable of.
 188        """
 189        # Note: The above are just default values and can/will be changed
 190        # upon update() when the attributes and type of the disk is actually
 191        # determined.
 192        self.tests: List[TestEntry] = []
 193        """
 194        **(list of `TestEntry`):** Contains the complete SMART self-test log
 195        for this device, as provided by smartctl.
 196        """
 197        self._test_running = False
 198        """
 199        **(bool):** True if a self-test is currently being run.
 200        False otherwise.
 201        """
 202        self._test_ECD = None
 203        """
 204        **(str):** Estimated completion time of the running SMART selftest.
 205        Not provided by SAS/SCSI devices.
 206        """
 207        self._test_progress = None
 208        """
 209        **(int):** Estimate progress percantage of the running SMART selftest.
 210        """
 211        self.diagnostics: Diagnostics = Diagnostics()
 212        """
 213        **Diagnostics** Contains parsed and processed diagnostic information
 214        extracted from the SMART information. Currently only populated for
 215        SAS and SCSI devices, since ATA/SATA SMART attributes are manufacturer
 216        proprietary.
 217        """
 218        self.temperature: Optional[int] = None
 219        """
 220        **(int or None): Since SCSI disks do not report attributes like ATA ones
 221        we need to grep/regex the shit outta the normal "smartctl -a" output.
 222        In case the device have more than one temperature sensor the first value
 223        will be stored here too.
 224        Note: Temperatures are always in Celsius (if possible).
 225        """
 226        self.temperatures: Dict[int, int] = {}
 227        """
 228        **(dict of int): NVMe disks usually report multiple temperatures, which
 229        will be stored here if available. Keys are sensor numbers as reported in
 230        output data.
 231        Note: Temperatures are always in Celsius (if possible).
 232        """
 233        self.logical_sector_size: Optional[int] = None
 234        """
 235        **(int):** The logical sector size of the device (or LBA).
 236        """
 237        self.physical_sector_size: Optional[int] = None
 238        """
 239        **(int):** The physical sector size of the device.
 240        """
 241        self.if_attributes: Union[None, NvmeAttributes] = None
 242        """
 243        **(NvmeAttributes):** This object may vary for each device interface attributes.
 244        It will store all data obtained from smartctl
 245        """
 246
 247        if self.name is None:
 248            warnings.warn(
 249                "\nDevice '{0}' does not exist! This object should be destroyed.".format(
 250                    name)
 251            )
 252            return
 253        # If no interface type was provided, scan for the device
 254        # Lets do this only for the non-abridged case
 255        # (we can work with no interface for abridged case)
 256        elif self._interface is None and not self.abridged:
 257            logger.trace(
 258                "Determining interface of disk: {0}".format(self.name))
 259            raw, returncode = self.smartctl.generic_call(
 260                ['-d', 'test', self.dev_reference])
 261
 262            if len(raw) > 0:
 263                # I do not like this parsing logic but it works for now!
 264                # just for reference _stdout.split('\n') gets us
 265                # something like
 266                # [
 267                #     ...copyright string...,
 268                #     '',
 269                #     "/dev/ada2: Device of type 'atacam' [ATA] detected",
 270                #     "/dev/ada2: Device of type 'atacam' [ATA] opened",
 271                #     ''
 272                # ]
 273                # The above example should be enough for anyone to understand the line below
 274                try:
 275                    for line in reversed(raw):
 276                        if "opened" in line:
 277                            self._interface = line.split("'")[1]
 278
 279                            if self._interface == "nvme":  # if nvme set SMART to true
 280                                self.smart_capable = True
 281                                self.smart_enabled = True
 282
 283                            break
 284                except:
 285                    # for whatever reason we could not get the interface type
 286                    # we should mark this as an `abbridged` case and move on
 287                    self._interface = None
 288                    self.abbridged = True
 289                # TODO: Uncomment the classify call if we ever find out that we need it
 290                # Disambiguate the generic interface to a specific type
 291                # self._classify()
 292            else:
 293                warnings.warn(
 294                    "\nDevice '{0}' does not exist! This object should be destroyed.".format(
 295                        name)
 296                )
 297                return
 298        # If a valid device was detected, populate its information
 299        # OR if in unabridged mode, then do it even without interface info
 300        if self._interface is not None or self.abridged:
 301            self.update()
 302
 303    @property
 304    def dev_interface(self) -> Optional[str]:
 305        """Returns the internal interface type of the device.
 306           It may not be the same as the interface type as used by smartctl.
 307
 308        Returns:
 309            str: The interface type of the device. (example: ata, scsi, nvme)
 310                 None if the interface type could not be determined.
 311        """
 312        # Try to get the fine-tuned interface type
 313        fineType = self._classify()
 314
 315        # If return still contains a megaraid, just asume it's type
 316        if 'megaraid' in fineType:
 317            # If any attributes is not None and has at least non None value, then it is a sat+megaraid device
 318            if self.attributes and any(self.attributes):
 319                return 'ata'
 320            else:
 321                return 'sas'
 322
 323        return fineType
 324
 325    @property
 326    def smartctl_interface(self) -> Optional[str]:
 327        """Returns the interface type of the device as it is used in smartctl.
 328
 329        Returns:
 330            str: The interface type of the device. (example: ata, scsi, nvme)
 331                 None if the interface type could not be determined.
 332        """
 333        return self._interface
 334
 335    @property
 336    def interface(self) -> Optional[str]:
 337        """Returns the interface type of the device as it is used in smartctl.
 338
 339        Returns:
 340            str: The interface type of the device. (example: ata, scsi, nvme)
 341                 None if the interface type could not be determined.
 342        """
 343        return self.smartctl_interface
 344
 345    @property
 346    def dev_reference(self) -> str:
 347        """The reference to the device as provided by smartctl.
 348           - On unix-like systems, this is the path to the device. (example /dev/<name>)
 349           - On MacOS, this is the name of the device. (example <name>)
 350           - On Windows, this is the drive letter of the device. (example <drive letter>)
 351
 352        Returns:
 353            str: The reference to the device as provided by smartctl.
 354        """
 355
 356        # detect if we are on MacOS
 357        if 'IOService' in self.name:
 358            return self.name
 359
 360        # otherwise asume we are on unix-like systems
 361        return os.path.join('/dev/', self.name)
 362
 363    @property
 364    def vendor(self) -> Optional[str]:
 365        """Returns the vendor of the device.
 366
 367        Returns:
 368            str: The vendor of the device.
 369        """
 370        if self._vendor:
 371            return self._vendor
 372
 373        # If family is present, try to stract from family. Skip anything but letters.
 374        elif self.family:
 375            filter = re.search(r'^[a-zA-Z]+', self.family.strip())
 376            if filter:
 377                return filter.group(0)
 378
 379        # If model is present, try to stract from model. Skip anything but letters.
 380        elif self.model:
 381            filter = re.search(r'^[a-zA-Z]+', self.model.strip())
 382            if filter:
 383                return filter.group(0)
 384
 385        # If all else fails, return None
 386        return None
 387
 388    @property
 389    def capacity(self) -> Optional[str]:
 390        """Returns the capacity in the raw smartctl format.
 391        This may be deprecated in the future and its only retained for compatibility.
 392
 393        Returns:
 394            str: The capacity in the raw smartctl format
 395        """
 396        return self._capacity_human
 397
 398    @property
 399    def diags(self) -> Dict[str, str]:
 400        """Gets the old/deprecated version of SCSI/SAS diags atribute.
 401        """
 402        return self.diagnostics.get_classic_format()
 403
 404    @property
 405    def size_raw(self) -> Optional[str]:
 406        """Returns the capacity in the raw smartctl format.
 407
 408        Returns:
 409            str: The capacity in the raw smartctl format
 410        """
 411        return self._capacity_human
 412
 413    @property
 414    def size(self) -> int:
 415        """Returns the capacity in bytes
 416
 417        Returns:
 418            int: The capacity in bytes
 419        """
 420        import humanfriendly
 421
 422        if self._capacity is not None:
 423            return self._capacity
 424        elif self._capacity_human is not None:
 425            return humanfriendly.parse_size(self._capacity_human)
 426        else:
 427            return 0
 428
 429    @property
 430    def sector_size(self) -> int:
 431        """Returns the sector size of the device.
 432
 433        Returns:
 434            int: The sector size of the device in Bytes. If undefined, we'll assume 512B
 435        """
 436        if self.logical_sector_size is not None:
 437            return self.logical_sector_size
 438        elif self.physical_sector_size is not None:
 439            return self.physical_sector_size
 440        else:
 441            return 512
 442
 443    def __repr__(self):
 444        """Define a basic representation of the class object."""
 445        return "<{0} device on /dev/{1} mod:{2} sn:{3}>".format(
 446            self._interface.upper() if self._interface else 'UNKNOWN INTERFACE',
 447            self.name,
 448            self.model,
 449            self.serial
 450        )
 451
 452    def __getstate__(self, all_info=True):
 453        """
 454        Allows us to send a pySMART Device object over a serializable
 455        medium which uses json (or the likes of json) payloads
 456        """
 457        state_dict = {
 458            'interface': self._interface if self._interface else 'UNKNOWN INTERFACE',
 459            'model': self.model,
 460            'firmware': self.firmware,
 461            'smart_capable': self.smart_capable,
 462            'smart_enabled': self.smart_enabled,
 463            'smart_status': self.assessment,
 464            'messages': self.messages,
 465            'test_capabilities': self.test_capabilities.copy(),
 466            'tests': [t.__getstate__() for t in self.tests] if self.tests else [],
 467            'diagnostics': self.diagnostics.__getstate__(),
 468            'temperature': self.temperature,
 469            'attributes': [attr.__getstate__() if attr else None for attr in self.attributes]
 470        }
 471        if all_info:
 472            state_dict.update({
 473                'name': self.name,
 474                'path': self.dev_reference,
 475                'serial': self.serial,
 476                'is_ssd': self.is_ssd,
 477                'rotation_rate': self.rotation_rate,
 478                'capacity': self._capacity_human
 479            })
 480        return state_dict
 481
 482    def __setstate__(self, state):
 483        state['assessment'] = state['smart_status']
 484        del state['smart_status']
 485        self.__dict__.update(state)
 486
 487    def smart_toggle(self, action: str) -> Tuple[bool, List[str]]:
 488        """
 489        A basic function to enable/disable SMART on device.
 490
 491        # Args:
 492        * **action (str):** Can be either 'on'(for enabling) or 'off'(for disabling).
 493
 494        # Returns"
 495        * **(bool):** Return True (if action succeded) else False
 496        * **(List[str]):** None if option succeded else contains the error message.
 497        """
 498        # Lets make the action verb all lower case
 499        if self._interface == 'nvme':
 500            return False, ['NVME devices do not currently support toggling SMART enabled']
 501        action_lower = action.lower()
 502        if action_lower not in ['on', 'off']:
 503            return False, ['Unsupported action {0}'.format(action)]
 504        # Now lets check if the device's smart enabled status is already that of what
 505        # the supplied action is intending it to be. If so then just return successfully
 506        if self.smart_enabled:
 507            if action_lower == 'on':
 508                return True, []
 509        else:
 510            if action_lower == 'off':
 511                return True, []
 512        if self._interface is not None:
 513            raw, returncode = self.smartctl.generic_call(
 514                ['-s', action_lower, '-d', self._interface, self.dev_reference])
 515        else:
 516            raw, returncode = self.smartctl.generic_call(
 517                ['-s', action_lower, self.dev_reference])
 518
 519        if returncode != 0:
 520            return False, raw
 521        # if everything worked out so far lets perform an update() and check the result
 522        self.update()
 523        if action_lower == 'off' and self.smart_enabled:
 524            return False, ['Failed to turn SMART off.']
 525        if action_lower == 'on' and not self.smart_enabled:
 526            return False, ['Failed to turn SMART on.']
 527        return True, []
 528
 529    def all_attributes(self, print_fn=print):
 530        """
 531        Prints the entire SMART attribute table, in a format similar to
 532        the output of smartctl.
 533        allows usage of custom print function via parameter print_fn by default uses print
 534        """
 535        header_printed = False
 536        for attr in self.attributes:
 537            if attr is not None:
 538                if not header_printed:
 539                    print_fn("{0:>3} {1:24}{2:4}{3:4}{4:4}{5:9}{6:8}{7:12}{8}"
 540                             .format('ID#', 'ATTRIBUTE_NAME', 'CUR', 'WST', 'THR', 'TYPE', 'UPDATED', 'WHEN_FAIL',
 541                                     'RAW'))
 542                    header_printed = True
 543                print_fn(attr)
 544        if not header_printed:
 545            print_fn('This device does not support SMART attributes.')
 546
 547    def all_selftests(self):
 548        """
 549        Prints the entire SMART self-test log, in a format similar to
 550        the output of smartctl.
 551        """
 552        if self.tests:
 553            all_tests = []
 554            if smartctl_type(self._interface) == 'scsi':
 555                header = "{0:3}{1:17}{2:23}{3:7}{4:14}{5:15}".format(
 556                    'ID',
 557                    'Test Description',
 558                    'Status',
 559                    'Hours',
 560                    '1st_Error@LBA',
 561                    '[SK  ASC  ASCQ]'
 562                )
 563            else:
 564                header = ("{0:3}{1:17}{2:30}{3:5}{4:7}{5:17}".format(
 565                    'ID',
 566                    'Test_Description',
 567                    'Status',
 568                    'Left',
 569                    'Hours',
 570                    '1st_Error@LBA'))
 571            all_tests.append(header)
 572            for test in self.tests:
 573                all_tests.append(str(test))
 574
 575            return all_tests
 576        else:
 577            no_tests = 'No self-tests have been logged for this device.'
 578            return no_tests
 579
 580    def _classify(self) -> str:
 581        """
 582        Disambiguates generic device types ATA and SCSI into more specific
 583        ATA, SATA, SAS, SAT and SCSI.
 584        """
 585
 586        fine_interface = self._interface or ''
 587        # SCSI devices might be SCSI, SAS or SAT
 588        # ATA device might be ATA or SATA
 589        if fine_interface in ['scsi', 'ata'] or 'megaraid' in fine_interface:
 590            if 'megaraid' in fine_interface:
 591                if not 'sat+' in fine_interface:
 592                    test = 'sat'+fine_interface
 593                else:
 594                    test = fine_interface
 595            else:
 596                test = 'sat' if fine_interface == 'scsi' else 'sata'
 597            # Look for a SATA PHY to detect SAT and SATA
 598            raw, returncode = self.smartctl.try_generic_call([
 599                '-d',
 600                smartctl_type(test),
 601                '-l',
 602                'sataphy',
 603                self.dev_reference])
 604
 605            if returncode == 0 and 'GP Log 0x11' in raw[3]:
 606                fine_interface = test
 607        # If device type is still SCSI (not changed to SAT above), then
 608        # check for a SAS PHY
 609        if fine_interface in ['scsi'] or 'megaraid' in fine_interface:
 610            raw, returncode = self.smartctl.try_generic_call([
 611                '-d',
 612                smartctl_type(fine_interface),
 613                '-l',
 614                'sasphy',
 615                self.dev_reference])
 616            if returncode == 0 and 'SAS SSP' in raw[4]:
 617                fine_interface = 'sas'
 618            # Some older SAS devices do not support the SAS PHY log command.
 619            # For these, see if smartmontools reports a transport protocol.
 620            else:
 621                raw = self.smartctl.all(self.dev_reference, fine_interface)
 622
 623                for line in raw:
 624                    if 'Transport protocol' in line and 'SAS' in line:
 625                        fine_interface = 'sas'
 626
 627        return fine_interface
 628
 629    def _guess_smart_type(self, line):
 630        """
 631        This function is not used in the generic wrapper, however the header
 632        is defined so that it can be monkey-patched by another application.
 633        """
 634        pass
 635
 636    def _make_smart_warnings(self):
 637        """
 638        Parses an ATA/SATA SMART table for attributes with the 'when_failed'
 639        value set. Generates an warning message for any such attributes and
 640        updates the self-assessment value if necessary.
 641        """
 642        if smartctl_type(self._interface) == 'scsi':
 643            return
 644        for attr in self.attributes:
 645            if attr is not None:
 646                if attr.when_failed == 'In_the_past':
 647                    warn_str = "{0} failed in the past with value {1}. [Threshold: {2}]".format(
 648                        attr.name, attr.worst, attr.thresh)
 649                    self.messages.append(warn_str)
 650                    if not self.assessment == 'FAIL':
 651                        self.assessment = 'WARN'
 652                elif attr.when_failed == 'FAILING_NOW':
 653                    warn_str = "{0} is failing now with value {1}. [Threshold: {2}]".format(
 654                        attr.name, attr.value, attr.thresh)
 655                    self.assessment = 'FAIL'
 656                    self.messages.append(warn_str)
 657                elif not attr.when_failed == '-':
 658                    warn_str = "{0} says it failed '{1}'. [V={2},W={3},T={4}]".format(
 659                        attr.name, attr.when_failed, attr.value, attr.worst, attr.thresh)
 660                    self.messages.append(warn_str)
 661                    if not self.assessment == 'FAIL':
 662                        self.assessment = 'WARN'
 663
 664    def get_selftest_result(self, output=None):
 665        """
 666        Refreshes a device's `pySMART.device.Device.tests` attribute to obtain
 667        the latest test results. If a new test result is obtained, its content
 668        is returned.
 669
 670        # Args:
 671        * **output (str, optional):** If set to 'str', the string
 672        representation of the most recent test result will be returned, instead
 673        of a `Test_Entry` object.
 674
 675        # Returns:
 676        * **(int):** Return status code. One of the following:
 677            * 0 - Success. Object (or optionally, string rep) is attached.
 678            * 1 - Self-test in progress. Must wait for it to finish.
 679            * 2 - No new test results.
 680            * 3 - The Self-test was Aborted by host
 681        * **(`Test_Entry` or str):** Most recent `Test_Entry` object (or
 682        optionally it's string representation) if new data exists.  Status
 683        message string on failure.
 684        * **(int):** Estimate progress percantage of the running SMART selftest, if known.
 685        Otherwise 'None'.
 686        """
 687        # SCSI self-test logs hold 20 entries while ATA logs hold 21
 688        if smartctl_type(self._interface) == 'scsi':
 689            maxlog = 20
 690        else:
 691            maxlog = 21
 692        # If we looked only at the most recent test result we could be fooled
 693        # by two short tests run close together (within the same hour)
 694        # appearing identical. Comparing the length of the log adds some
 695        # confidence until it maxes, as above. Comparing the least-recent test
 696        # result greatly diminishes the chances that two sets of two tests each
 697        # were run within an hour of themselves, but with 16-17 other tests run
 698        # in between them.
 699        if self.tests:
 700            _first_entry = self.tests[0]
 701            _len = len(self.tests)
 702            _last_entry = self.tests[_len - 1]
 703        else:
 704            _len = 0
 705        self.update()
 706        # Since I have changed the update() parsing to DTRT to pickup currently
 707        # running selftests we can now purely rely on that for self._test_running
 708        # Thus check for that variable first and return if it is True with appropos message.
 709        if self._test_running is True:
 710            return 1, 'Self-test in progress. Please wait.', self._test_progress
 711        # Check whether the list got longer (ie: new entry)
 712        # If so return the newest test result
 713        # If not, because it's max size already, check for new entries
 714        if (
 715                (len(self.tests) != _len) or
 716                (
 717                    len == maxlog and
 718                    (
 719                        _first_entry.type != self.tests[0].type or
 720                        _first_entry.hours != self.tests[0].hours or
 721                        _last_entry.type != self.tests[len(self.tests) - 1].type or
 722                        _last_entry.hours != self.tests[len(
 723                            self.tests) - 1].hours
 724                    )
 725                )
 726        ):
 727            return (
 728                0 if 'Aborted' not in self.tests[0].status else 3,
 729                str(self.tests[0]) if output == 'str' else self.tests[0],
 730                None
 731            )
 732        else:
 733            return 2, 'No new self-test results found.', None
 734
 735    def abort_selftest(self):
 736        """
 737        Aborts non-captive SMART Self Tests.   Note that this command
 738        will  abort the Offline Immediate Test routine only if your disk
 739        has the "Abort Offline collection upon new command"  capability.
 740
 741        # Args: Nothing (just aborts directly)
 742
 743        # Returns:
 744        * **(int):** The returncode of calling `smartctl -X device_path`
 745        """
 746        return self.smartctl.test_stop(smartctl_type(self._interface), self.dev_reference)
 747
 748    def run_selftest(self, test_type, ETA_type='date'):
 749        """
 750        Instructs a device to begin a SMART self-test. All tests are run in
 751        'offline' / 'background' mode, allowing normal use of the device while
 752        it is being tested.
 753
 754        # Args:
 755        * **test_type (str):** The type of test to run. Accepts the following
 756        (not case sensitive):
 757            * **short** - Brief electo-mechanical functionality check.
 758            Generally takes 2 minutes or less.
 759            * **long** - Thorough electro-mechanical functionality check,
 760            including complete recording media scan. Generally takes several
 761            hours.
 762            * **conveyance** - Brief test used to identify damage incurred in
 763            shipping. Generally takes 5 minutes or less. **This test is not
 764            supported by SAS or SCSI devices.**
 765            * **offline** - Runs SMART Immediate Offline Test. The effects of
 766            this test are visible only in that it updates the SMART Attribute
 767            values, and if errors are found they will appear in the SMART error
 768            log, visible with the '-l error' option to smartctl. **This test is
 769            not supported by SAS or SCSI devices in pySMART use cli smartctl for
 770            running 'offline' selftest (runs in foreground) on scsi devices.**
 771            * **ETA_type** - Format to return the estimated completion time/date
 772            in. Default is 'date'. One could otherwise specidy 'seconds'.
 773            Again only for ATA devices.
 774
 775        # Returns:
 776        * **(int):** Return status code.  One of the following:
 777            * 0 - Self-test initiated successfully
 778            * 1 - Previous self-test running. Must wait for it to finish.
 779            * 2 - Unknown or unsupported (by the device) test type requested.
 780            * 3 - Unspecified smartctl error. Self-test not initiated.
 781        * **(str):** Return status message.
 782        * **(str)/(float):** Estimated self-test completion time if a test is started.
 783        The optional argument of 'ETA_type' (see above) controls the return type.
 784        if 'ETA_type' == 'date' then a date string is returned else seconds(float)
 785        is returned.
 786        Note: The self-test completion time can only be obtained for ata devices.
 787        Otherwise 'None'.
 788        """
 789        # Lets call get_selftest_result() here since it does an update() and
 790        # checks for an existing selftest is running or not, this way the user
 791        # can issue a test from the cli and this can still pick that up
 792        # Also note that we do not need to obtain the results from this as the
 793        # data is already stored in the Device class object's variables
 794        self.get_selftest_result()
 795        if self._test_running:
 796            return 1, 'Self-test in progress. Please wait.', self._test_ECD
 797        test_type = test_type.lower()
 798        interface = smartctl_type(self._interface)
 799        try:
 800            if not self.test_capabilities[test_type]:
 801                return (
 802                    2,
 803                    "Device {0} does not support the '{1}' test ".format(
 804                        self.name, test_type),
 805                    None
 806                )
 807        except KeyError:
 808            return 2, "Unknown test type '{0}' requested.".format(test_type), None
 809
 810        raw, rc = self.smartctl.test_start(
 811            interface, test_type, self.dev_reference)
 812        _success = False
 813        _running = False
 814        for line in raw:
 815            if 'has begun' in line:
 816                _success = True
 817                self._test_running = True
 818            if 'aborting current test' in line:
 819                _running = True
 820                try:
 821                    self._test_progress = 100 - \
 822                        int(line.split('(')[-1].split('%')[0])
 823                except ValueError:
 824                    pass
 825
 826            if _success and 'complete after' in line:
 827                self._test_ECD = line[25:].rstrip()
 828                if ETA_type == 'seconds':
 829                    self._test_ECD = mktime(
 830                        strptime(self._test_ECD, '%a %b %d %H:%M:%S %Y')) - time()
 831                self._test_progress = 0
 832        if _success:
 833            return 0, 'Self-test started successfully', self._test_ECD
 834        else:
 835            if _running:
 836                return 1, 'Self-test already in progress. Please wait.', self._test_ECD
 837            else:
 838                return 3, 'Unspecified Error. Self-test not started.', None
 839
 840    def run_selftest_and_wait(self, test_type, output=None, polling=5, progress_handler=None):
 841        """
 842        This is essentially a wrapper around run_selftest() such that we
 843        call self.run_selftest() and wait on the running selftest till
 844        it finished before returning.
 845        The above holds true for all pySMART supported tests with the
 846        exception of the 'offline' test (ATA only) as it immediately
 847        returns, since the entire test only affects the smart error log
 848        (if any errors found) and updates the SMART attributes. Other
 849        than that it is not visibile anywhere else, so we start it and
 850        simply return.
 851        # Args:
 852        * **test_type (str):** The type of test to run. Accepts the following
 853        (not case sensitive):
 854            * **short** - Brief electo-mechanical functionality check.
 855            Generally takes 2 minutes or less.
 856            * **long** - Thorough electro-mechanical functionality check,
 857            including complete recording media scan. Generally takes several
 858            hours.
 859            * **conveyance** - Brief test used to identify damage incurred in
 860            shipping. Generally takes 5 minutes or less. **This test is not
 861            supported by SAS or SCSI devices.**
 862            * **offline** - Runs SMART Immediate Offline Test. The effects of
 863            this test are visible only in that it updates the SMART Attribute
 864            values, and if errors are found they will appear in the SMART error
 865            log, visible with the '-l error' option to smartctl. **This test is
 866            not supported by SAS or SCSI devices in pySMART use cli smartctl for
 867            running 'offline' selftest (runs in foreground) on scsi devices.**
 868        * **output (str, optional):** If set to 'str', the string
 869            representation of the most recent test result will be returned,
 870            instead of a `Test_Entry` object.
 871        * **polling (int, default=5):** The time duration to sleep for between
 872            checking for test_results and progress.
 873        * **progress_handler (function, optional):** This if provided is called
 874            with self._test_progress as the supplied argument everytime a poll to
 875            check the status of the selftest is done.
 876        # Returns:
 877        * **(int):** Return status code.  One of the following:
 878            * 0 - Self-test executed and finished successfully
 879            * 1 - Previous self-test running. Must wait for it to finish.
 880            * 2 - Unknown or illegal test type requested.
 881            * 3 - The Self-test was Aborted by host
 882            * 4 - Unspecified smartctl error. Self-test not initiated.
 883        * **(`Test_Entry` or str):** Most recent `Test_Entry` object (or
 884        optionally it's string representation) if new data exists.  Status
 885        message string on failure.
 886        """
 887        test_initiation_result = self.run_selftest(test_type)
 888        if test_initiation_result[0] != 0:
 889            return test_initiation_result[:2]
 890        if test_type == 'offline':
 891            self._test_running = False
 892        # if not then the test initiated correctly and we can start the polling.
 893        # For now default 'polling' value is 5 seconds if not specified by the user
 894
 895        # Do an initial check, for good measure.
 896        # In the probably impossible case that self._test_running is instantly False...
 897        selftest_results = self.get_selftest_result(output=output)
 898        while self._test_running:
 899            if selftest_results[0] != 1:
 900                # the selftest is run and finished lets return with the results
 901                break
 902            # Otherwise see if we are provided with the progress_handler to update progress
 903            if progress_handler is not None:
 904                progress_handler(
 905                    selftest_results[2] if selftest_results[2] is not None else 50)
 906            # Now sleep 'polling' seconds before checking the progress again
 907            sleep(polling)
 908
 909            # Check after the sleep to ensure we return the right result, and not an old one.
 910            selftest_results = self.get_selftest_result(output=output)
 911
 912        # Now if (selftes_results[0] == 2) i.e No new selftest (because the same
 913        # selftest was run twice within the last hour) but we know for a fact that
 914        # we just ran a new selftest then just return the latest entry in self.tests
 915        if selftest_results[0] == 2:
 916            selftest_return_value = 0 if 'Aborted' not in self.tests[0].status else 3
 917            return selftest_return_value, str(self.tests[0]) if output == 'str' else self.tests[0]
 918        return selftest_results[:2]
 919
 920    def update(self):
 921        """
 922        Queries for device information using smartctl and updates all
 923        class members, including the SMART attribute table and self-test log.
 924        Can be called at any time to refresh the `pySMART.device.Device`
 925        object's data content.
 926        """
 927        # set temperature back to None so that if update() is called more than once
 928        # any logic that relies on self.temperature to be None to rescan it works.it
 929        self.temperature = None
 930        # same for temperatures
 931        self.temperatures = {}
 932        if self.abridged:
 933            interface = None
 934            raw = self.smartctl.info(self.dev_reference)
 935
 936        else:
 937            interface = smartctl_type(self._interface)
 938            raw = self.smartctl.all(
 939                self.dev_reference, interface)
 940
 941        parse_self_tests = False
 942        parse_running_test = False
 943        parse_ascq = False
 944        message = ''
 945        self.tests = []
 946        self._test_running = False
 947        self._test_progress = None
 948        # Lets skip the first couple of non-useful lines
 949        _stdout = raw[4:]
 950
 951        #######################################
 952        #           Encoding fixing           #
 953        #######################################
 954        # In some scenarios, smartctl returns some lines with a different/strange encoding
 955        # This is a workaround to fix that
 956        for i, line in enumerate(_stdout):
 957            # character ' ' (U+202F) should be removed
 958            _stdout[i] = line.replace('\u202f', '')
 959
 960        #######################################
 961        #   Dedicated interface attributes    #
 962        #######################################
 963
 964        if interface == 'nvme':
 965            self.if_attributes = NvmeAttributes(iter(_stdout))
 966
 967            # Get Tests
 968            for test in self.if_attributes.tests:
 969                self.tests.append(TestEntry('nvme', test.num, test.description, test.status, test.powerOnHours,
 970                                  test.failingLBA, nsid=test.nsid, sct=test.sct, code=test.code, remain=100-test.progress))
 971
 972            # Set running test
 973            if any(test.status == 'Running' for test in self.if_attributes.tests):
 974                self._test_running = True
 975                self._test_progress = self.if_attributes.tests[0].progress
 976            else:
 977                self._test_running = False
 978                self._test_progress = None
 979
 980        else:
 981            self.if_attributes = None
 982
 983        #######################################
 984        #    Global / generic  attributes     #
 985        #######################################
 986        stdout_iter = iter(_stdout)
 987        for line in stdout_iter:
 988            if line.strip() == '':  # Blank line stops sub-captures
 989                if parse_self_tests is True:
 990                    parse_self_tests = False
 991                if parse_ascq:
 992                    parse_ascq = False
 993                    self.messages.append(message)
 994            if parse_ascq:
 995                message += ' ' + line.lstrip().rstrip()
 996            if parse_self_tests:
 997                # Detect Test Format
 998
 999                ## SCSI/SAS FORMAT ##
1000                # Example smartctl output
1001                # SMART Self-test log
1002                # Num  Test              Status                 segment  LifeTime  LBA_first_err [SK ASC ASQ]
1003                #      Description                              number   (hours)
1004                # # 1  Background short  Completed                   -   33124                 - [-   -    -]
1005                format_scsi = re.compile(
1006                    r'^[#\s]*(\d+)\s{2,}(.*[^\s])\s{2,}(.*[^\s])\s{2,}(.*[^\s])\s{2,}(.*[^\s])\s{2,}(.*[^\s])\s+\[([^\s]+)\s+([^\s]+)\s+([^\s]+)\]$').match(line)
1007
1008                ## ATA FORMAT ##
1009                # Example smartctl output:
1010                # SMART Self-test log structure revision number 1
1011                # Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
1012                # # 1  Extended offline    Completed without error       00%     46660         -
1013                format_ata = re.compile(
1014                    r'^[#\s]*(\d+)\s{2,}(.*[^\s])\s{2,}(.*[^\s])\s{1,}(.*[^\s])\s{2,}(.*[^\s])\s{2,}(.*[^\s])$').match(line)
1015
1016                if format_scsi is not None:
1017                    format = 'scsi'
1018                    parsed = format_scsi.groups()
1019                    num = int(parsed[0])
1020                    test_type = parsed[1]
1021                    status = parsed[2]
1022                    segment = parsed[3]
1023                    hours = parsed[4]
1024                    lba = parsed[5]
1025                    sense = parsed[6]
1026                    asc = parsed[7]
1027                    ascq = parsed[8]
1028                    self.tests.append(TestEntry(
1029                        format,
1030                        num,
1031                        test_type,
1032                        status,
1033                        hours,
1034                        lba,
1035                        segment=segment,
1036                        sense=sense,
1037                        asc=asc,
1038                        ascq=ascq
1039                    ))
1040                elif format_ata is not None:
1041                    ## ATA FORMAT ##
1042                    format = 'ata'
1043                    parsed = format_ata.groups()
1044                    num = parsed[0]
1045                    test_type = parsed[1]
1046                    status = parsed[2]
1047                    remain = parsed[3]
1048                    hours = parsed[4]
1049                    lba = parsed[5]
1050
1051                    try:
1052                        num = int(num)
1053                    except:
1054                        num = None
1055
1056                    self.tests.append(
1057                        TestEntry(format, num, test_type, status,
1058                                  hours, lba, remain=remain)
1059                    )
1060                else:
1061                    pass
1062
1063            # Basic device information parsing
1064            if any_in(line, 'Device Model', 'Product', 'Model Number'):
1065                self.model = line.split(':')[1].lstrip().rstrip()
1066                self._guess_smart_type(line.lower())
1067                continue
1068
1069            if 'Model Family' in line:
1070                self.family = line.split(':')[1].strip()
1071                self._guess_smart_type(line.lower())
1072                continue
1073
1074            if 'LU WWN' in line:
1075                self._guess_smart_type(line.lower())
1076                continue
1077
1078            if any_in(line, 'Serial Number', 'Serial number'):
1079                try:
1080                    self.serial = line.split(':')[1].split()[0].rstrip()
1081                except IndexError:
1082                    # Serial reported empty
1083                    self.serial = ""
1084                continue
1085
1086            vendor = re.compile(r'^Vendor:\s+(\w+)').match(line)
1087            if vendor is not None:
1088                self._vendor = vendor.groups()[0]
1089
1090            if any_in(line, 'Firmware Version', 'Revision'):
1091                self.firmware = line.split(':')[1].strip()
1092
1093            if any_in(line, 'User Capacity', 'Total NVM Capacity', 'Namespace 1 Size/Capacity'):
1094                # TODO: support for multiple NVMe namespaces
1095                m = re.match(
1096                    r'.*:\s+([\d,. \u2019\u00a0]+)\s\D*\[?([^\]]+)?\]?', line.strip())
1097
1098                if m is not None:
1099                    tmp = m.groups()
1100                    self._capacity = int(
1101                        tmp[0].strip().replace(',', '').replace('.', '').replace(' ', '').replace('\u2019', '').replace('\u00a0', ''))
1102
1103                    if len(tmp) == 2 and tmp[1] is not None:
1104                        self._capacity_human = tmp[1].strip().replace(',', '.')
1105
1106            if 'SMART support' in line:
1107                # self.smart_capable = 'Available' in line
1108                # self.smart_enabled = 'Enabled' in line
1109                # Since this line repeats twice the above method is flawed
1110                # Lets try the following instead, it is a bit redundant but
1111                # more robust.
1112                if any_in(line, 'Unavailable', 'device lacks SMART capability'):
1113                    self.smart_capable = False
1114                    self.smart_enabled = False
1115                elif 'Enabled' in line:
1116                    self.smart_enabled = True
1117                elif 'Disabled' in line:
1118                    self.smart_enabled = False
1119                elif any_in(line, 'Available', 'device has SMART capability'):
1120                    self.smart_capable = True
1121                continue
1122
1123            if 'does not support SMART' in line:
1124                self.smart_capable = False
1125                self.smart_enabled = False
1126                continue
1127
1128            if 'Rotation Rate' in line:
1129                if 'Solid State Device' in line:
1130                    self.is_ssd = True
1131                elif 'rpm' in line:
1132                    self.is_ssd = False
1133                    try:
1134                        self.rotation_rate = int(
1135                            line.split(':')[1].lstrip().rstrip()[:-4])
1136                    except ValueError:
1137                        # Cannot parse the RPM? Assigning None instead
1138                        self.rotation_rate = None
1139                continue
1140
1141            if 'SMART overall-health self-assessment' in line:  # ATA devices
1142                if line.split(':')[1].strip() == 'PASSED':
1143                    self.assessment = 'PASS'
1144                else:
1145                    self.assessment = 'FAIL'
1146                continue
1147
1148            if 'SMART Health Status' in line:  # SCSI devices
1149                if line.split(':')[1].strip() == 'OK':
1150                    self.assessment = 'PASS'
1151                else:
1152                    self.assessment = 'FAIL'
1153                    parse_ascq = True  # Set flag to capture status message
1154                    message = line.split(':')[1].lstrip().rstrip()
1155                continue
1156
1157            # Parse SMART test capabilities (ATA only)
1158            # Note: SCSI does not list this but and allows for only 'offline', 'short' and 'long'
1159            if 'SMART execute Offline immediate' in line:
1160                self.test_capabilities['offline'] = 'No' not in line
1161                continue
1162
1163            if 'Conveyance Self-test supported' in line:
1164                self.test_capabilities['conveyance'] = 'No' not in line
1165                continue
1166
1167            if 'Selective Self-test supported' in line:
1168                self.test_capabilities['selective'] = 'No' not in line
1169                continue
1170
1171            if 'Self-test supported' in line:
1172                self.test_capabilities['short'] = 'No' not in line
1173                self.test_capabilities['long'] = 'No' not in line
1174                continue
1175
1176            # Parse SMART test capabilities (NVMe only)
1177            if 'Optional Admin Commands' in line:
1178                if 'Self_Test' in line:
1179                    self.test_capabilities['short'] = True
1180                    self.test_capabilities['long'] = True
1181
1182            # SMART Attribute table parsing
1183            if 'Specific SMART Attributes' in line:
1184                attribute_re = re.compile(
1185                    r'^\s*(?P<id>\d+)\s+(?P<name>\S+)\s+(?P<flag>\S+)\s+(?P<value>\d+)\s+(?P<worst>\d+)\s+(?P<thresh>\S+)\s+(?P<type>\S+)\s+(?P<updated>\S+)\s+(?P<whenfailed>\S+)\s+(?P<raw>.+)$')
1186
1187                # loop until we reach the end of the table (empty line)
1188                while True:
1189                    line = next(stdout_iter).strip()
1190                    if line == '':
1191                        break
1192
1193                    # Parse the line
1194                    m = attribute_re.match(line)
1195                    if m is not None:
1196                        tmp = m.groupdict()
1197                        self.attributes[int(tmp['id'])] = Attribute(
1198                            int(tmp['id']), tmp['name'], int(tmp['flag'], base=16), tmp['value'], tmp['worst'], tmp['thresh'], tmp['type'], tmp['updated'], tmp['whenfailed'], tmp['raw'])
1199
1200            # For some reason smartctl does not show a currently running test
1201            # for 'ATA' in the Test log so I just have to catch it this way i guess!
1202            # For 'scsi' I still do it since it is the only place I get % remaining in scsi
1203            if 'Self-test execution status' in line:
1204                if 'progress' in line:
1205                    self._test_running = True
1206                    # for ATA the "%" remaining is on the next line
1207                    # thus set the parse_running_test flag and move on
1208                    parse_running_test = True
1209                elif '%' in line:
1210                    # for scsi the progress is on the same line
1211                    # so we can just parse it and move on
1212                    self._test_running = True
1213                    try:
1214                        self._test_progress = 100 - \
1215                            int(line.split('%')[0][-3:].strip())
1216                    except ValueError:
1217                        pass
1218                continue
1219            if parse_running_test is True:
1220                try:
1221                    self._test_progress = 100 - \
1222                        int(line.split('%')[0][-3:].strip())
1223                except ValueError:
1224                    pass
1225                parse_running_test = False
1226
1227            if "Self-test log" in line:
1228                parse_self_tests = True  # Set flag to capture test entries
1229                continue
1230
1231            #######################################
1232            #              SCSI only              #
1233            #######################################
1234            #
1235            # Everything from here on is parsing SCSI information that takes
1236            # the place of similar ATA SMART information
1237            if 'used endurance' in line:
1238                pct = int(line.split(':')[1].strip()[:-1])
1239                self.diagnostics.Life_Left = 100 - pct
1240                continue
1241
1242            if 'Specified cycle count' in line:
1243                self.diagnostics.Start_Stop_Spec = int(
1244                    line.split(':')[1].strip())
1245                continue
1246
1247            if 'Accumulated start-stop cycles' in line:
1248                self.diagnostics.Start_Stop_Cycles = int(
1249                    line.split(':')[1].strip())
1250                if self.diagnostics.Start_Stop_Spec and self.diagnostics.Start_Stop_Spec != 0:
1251                    self.diagnostics.Start_Stop_Pct_Left = int(round(
1252                        100 - (self.diagnostics.Start_Stop_Cycles /
1253                               self.diagnostics.Start_Stop_Spec), 0))
1254                continue
1255
1256            if 'Specified load-unload count' in line:
1257                self.diagnostics.Load_Cycle_Spec = int(
1258                    line.split(':')[1].strip())
1259                continue
1260
1261            if 'Accumulated load-unload cycles' in line:
1262                self.diagnostics.Load_Cycle_Count = int(
1263                    line.split(':')[1].strip())
1264                if self.diagnostics.Load_Cycle_Spec and self.diagnostics.Load_Cycle_Spec != 0:
1265                    self.diagnostics.Load_Cycle_Pct_Left = int(round(
1266                        100 - (self.diagnostics.Load_Cycle_Count /
1267                               self.diagnostics.Load_Cycle_Spec), 0))
1268                continue
1269
1270            if 'Elements in grown defect list' in line:
1271                self.diagnostics.Reallocated_Sector_Ct = int(
1272                    line.split(':')[1].strip())
1273                continue
1274
1275            if 'read:' in line:
1276                line_ = ' '.join(line.split()).split(' ')
1277                if line_[1] == '0' and line_[2] == '0' and line_[3] == '0' and line_[4] == '0':
1278                    self.diagnostics.Corrected_Reads = 0
1279                elif line_[4] == '0':
1280                    self.diagnostics.Corrected_Reads = int(
1281                        line_[1]) + int(line_[2]) + int(line_[3])
1282                else:
1283                    self.diagnostics.Corrected_Reads = int(line_[4])
1284                self.diagnostics._Reads_GB = float(line_[6].replace(',', '.'))
1285                self.diagnostics._Uncorrected_Reads = int(line_[7])
1286                continue
1287
1288            if 'write:' in line:
1289                line_ = ' '.join(line.split()).split(' ')
1290                if (line_[1] == '0' and line_[2] == '0' and
1291                        line_[3] == '0' and line_[4] == '0'):
1292                    self.diagnostics.Corrected_Writes = 0
1293                elif line_[4] == '0':
1294                    self.diagnostics.Corrected_Writes = int(
1295                        line_[1]) + int(line_[2]) + int(line_[3])
1296                else:
1297                    self.diagnostics.Corrected_Writes = int(line_[4])
1298                self.diagnostics._Writes_GB = float(line_[6].replace(',', '.'))
1299                self.diagnostics._Uncorrected_Writes = int(line_[7])
1300                continue
1301
1302            if 'verify:' in line:
1303                line_ = ' '.join(line.split()).split(' ')
1304                if (line_[1] == '0' and line_[2] == '0' and
1305                        line_[3] == '0' and line_[4] == '0'):
1306                    self.diagnostics.Corrected_Verifies = 0
1307                elif line_[4] == '0':
1308                    self.diagnostics.Corrected_Verifies = int(
1309                        line_[1]) + int(line_[2]) + int(line_[3])
1310                else:
1311                    self.diagnostics.Corrected_Verifies = int(line_[4])
1312                self.diagnostics._Verifies_GB = float(
1313                    line_[6].replace(',', '.'))
1314                self.diagnostics._Uncorrected_Verifies = int(line_[7])
1315                continue
1316
1317            if 'non-medium error count' in line:
1318                self.diagnostics.Non_Medium_Errors = int(
1319                    line.split(':')[1].strip())
1320                continue
1321
1322            if 'Accumulated power on time' in line:
1323                self.diagnostics.Power_On_Hours = int(
1324                    line.split(':')[1].split(' ')[1])
1325                continue
1326
1327            if 'Current Drive Temperature' in line or ('Temperature:' in
1328                                                       line and interface == 'nvme'):
1329                try:
1330                    self.temperature = int(
1331                        line.split(':')[-1].strip().split()[0])
1332
1333                    if 'fahrenheit' in line.lower():
1334                        self.temperature = int((self.temperature - 32) * 5 / 9)
1335
1336                except ValueError:
1337                    pass
1338
1339                continue
1340
1341            if 'Temperature Sensor ' in line:
1342                try:
1343                    match = re.search(
1344                        r'Temperature\sSensor\s([0-9]+):\s+(-?[0-9]+)', line)
1345                    if match:
1346                        (tempsensor_number_s, tempsensor_value_s) = match.group(1, 2)
1347                        tempsensor_number = int(tempsensor_number_s)
1348                        tempsensor_value = int(tempsensor_value_s)
1349
1350                        if 'fahrenheit' in line.lower():
1351                            tempsensor_value = int(
1352                                (tempsensor_value - 32) * 5 / 9)
1353
1354                        self.temperatures[tempsensor_number] = tempsensor_value
1355                        if self.temperature is None or tempsensor_number == 0:
1356                            self.temperature = tempsensor_value
1357                except ValueError:
1358                    pass
1359
1360                continue
1361
1362            #######################################
1363            #            Common values            #
1364            #######################################
1365
1366            # Sector sizes
1367            if 'Sector Sizes' in line:  # ATA
1368                m = re.match(
1369                    r'.* (\d+) bytes logical,\s*(\d+) bytes physical', line)
1370                if m:
1371                    self.logical_sector_size = int(m.group(1))
1372                    self.physical_sector_size = int(m.group(2))
1373                    # set diagnostics block size to physical sector size
1374                    self.diagnostics._block_size = self.physical_sector_size
1375                continue
1376            if 'Logical block size:' in line:  # SCSI 1/2
1377                self.logical_sector_size = int(
1378                    line.split(':')[1].strip().split(' ')[0])
1379                # set diagnostics block size to logical sector size
1380                self.diagnostics._block_size = self.logical_sector_size
1381                continue
1382            if 'Physical block size:' in line:  # SCSI 2/2
1383                self.physical_sector_size = int(
1384                    line.split(':')[1].strip().split(' ')[0])
1385                continue
1386            if 'Namespace 1 Formatted LBA Size' in line:  # NVMe
1387                # Note: we will assume that there is only one namespace
1388                self.logical_sector_size = int(
1389                    line.split(':')[1].strip().split(' ')[0])
1390                continue
1391
1392        if not self.abridged:
1393            if not interface == 'scsi':
1394                # Parse the SMART table for below-threshold attributes and create
1395                # corresponding warnings for non-SCSI disks
1396                self._make_smart_warnings()
1397            else:
1398                # If not obtained Power_On_Hours above, make a direct attempt to extract power on
1399                # hours from the background scan results log.
1400                if self.diagnostics.Power_On_Hours is None:
1401                    raw, returncode = self.smartctl.generic_call(
1402                        [
1403                            '-d',
1404                            'scsi',
1405                            '-l',
1406                            'background',
1407                            self.dev_reference
1408                        ])
1409
1410                    for line in raw:
1411                        if 'power on time' in line:
1412                            self.diagnostics.Power_On_Hours = int(
1413                                line.split(':')[1].split(' ')[1])
1414        # map temperature
1415        if self.temperature is None:
1416            # in this case the disk is probably ata
1417            try:
1418                # Some disks report temperature to attribute number 190 ('Airflow_Temperature_Cel')
1419                # see https://bugs.freenas.org/issues/20860
1420                temp_attr = self.attributes[194] or self.attributes[190]
1421                if temp_attr is not None and temp_attr.raw_int is not None:
1422                    self.temperature = temp_attr.raw_int
1423            except (ValueError, AttributeError):
1424                pass
1425        # Now that we have finished the update routine, if we did not find a runnning selftest
1426        # nuke the self._test_ECD and self._test_progress
1427        if self._test_running is False:
1428            self._test_ECD = None
1429            self._test_progress = None

Represents any device attached to an internal storage interface, such as a hard drive or DVD-ROM, and detected by smartmontools. Includes eSATA (considered SATA) but excludes other external devices (USB, Firewire).

Device( name: str, interface: Optional[str] = None, abridged: bool = False, smart_options: Union[str, List[str], NoneType] = None, smartctl: pySMART.smartctl.Smartctl = <pySMART.smartctl.Smartctl object>)
 88    def __init__(self, name: str, interface: Optional[str] = None, abridged: bool = False, smart_options: Union[str, List[str], None] = None, smartctl: Smartctl = SMARTCTL):
 89        """Instantiates and initializes the `pySMART.device.Device`."""
 90        if not (
 91                interface is None or
 92                smartctl_isvalid_type(interface.lower())
 93        ):
 94            raise ValueError(
 95                'Unknown interface: {0} specified for {1}'.format(interface, name))
 96        self.abridged = abridged or interface == 'UNKNOWN INTERFACE'
 97        if smart_options is not None:
 98            if isinstance(smart_options,  str):
 99                smart_options = smart_options.split(' ')
100            smartctl.add_options(smart_options)
101        self.smartctl = smartctl
102        """
103        """
104        self.name: str = name.replace('/dev/', '').replace('nvd', 'nvme')
105        """
106        **(str):** Device's hardware ID, without the '/dev/' prefix.
107        (ie: sda (Linux), pd0 (Windows))
108        """
109        self.family: Optional[str] = None
110        """**(str):** Device's family (if any)."""
111        self.model: Optional[str] = None
112        """**(str):** Device's model number (if any)."""
113        self.serial: Optional[str] = None
114        """**(str):** Device's serial number (if any)."""
115        self._vendor: Optional[str] = None
116        """**(str):** Device's vendor (if any)."""
117        self._interface: Optional[str] = None if interface == 'UNKNOWN INTERFACE' else interface
118        """
119        **(str):** Device's interface type. Must be one of:
120            * **ATA** - Advanced Technology Attachment
121            * **SATA** - Serial ATA
122            * **SCSI** - Small Computer Systems Interface
123            * **SAS** - Serial Attached SCSI
124            * **SAT** - SCSI-to-ATA Translation (SATA device plugged into a
125            SAS port)
126            * **CSMI** - Common Storage Management Interface (Intel ICH /
127            Matrix RAID)
128        Generally this should not be specified to allow auto-detection to
129        occur. Otherwise, this value overrides the auto-detected type and could
130        produce unexpected or no data.
131        """
132        self._capacity: Optional[int] = None
133        """**(str):** Device's user capacity as reported directly by smartctl (RAW)."""
134        self._capacity_human: Optional[str] = None
135        """**(str):** Device's user capacity (human readable) as reported directly by smartctl (RAW)."""
136        self.firmware: Optional[str] = None
137        """**(str):** Device's firmware version."""
138        self.smart_capable: bool = 'nvme' in self.name
139        """
140        **(bool):** True if the device has SMART Support Available.
141        False otherwise. This is useful for VMs amongst other things.
142        """
143        self.smart_enabled: bool = 'nvme' in self.name
144        """
145        **(bool):** True if the device supports SMART (or SCSI equivalent) and
146        has the feature set enabled. False otherwise.
147        """
148        self.assessment: Optional[str] = None
149        """
150        **(str):** SMART health self-assessment as reported by the device.
151        """
152        self.messages: List[str] = []
153        """
154        **(list of str):** Contains any SMART warnings or other error messages
155        reported by the device (ie: ascq codes).
156        """
157        self.is_ssd: bool = True if 'nvme' in self.name else False
158        """
159        **(bool):** True if this device is a Solid State Drive.
160        False otherwise.
161        """
162        self.rotation_rate: Optional[int] = None
163        """
164        **(int):** The Roatation Rate of the Drive if it is not a SSD.
165        The Metric is RPM.
166        """
167        self.attributes: List[Optional[Attribute]] = [None] * 256
168        """
169        **(list of `Attribute`):** Contains the complete SMART table
170        information for this device, as provided by smartctl. Indexed by
171        attribute #, values are set to 'None' for attributes not suported by
172        this device.
173        """
174        self.test_capabilities = {
175            'offline': False,  # SMART execute Offline immediate (ATA only)
176            'short': 'nvme' not in self.name,  # SMART short Self-test
177            'long': 'nvme' not in self.name,  # SMART long Self-test
178            'conveyance': False,  # SMART Conveyance Self-Test (ATA only)
179            'selective': False,  # SMART Selective Self-Test (ATA only)
180        }
181        # Note have not included 'offline' test for scsi as it runs in the foregorund
182        # mode. While this may be beneficial to us in someways it is against the
183        # general layout and pattern that the other tests issued using pySMART are
184        # followed hence not doing it currently
185        """
186        **(dict): ** This dictionary contains key == 'Test Name' and
187        value == 'True/False' of self-tests that this device is capable of.
188        """
189        # Note: The above are just default values and can/will be changed
190        # upon update() when the attributes and type of the disk is actually
191        # determined.
192        self.tests: List[TestEntry] = []
193        """
194        **(list of `TestEntry`):** Contains the complete SMART self-test log
195        for this device, as provided by smartctl.
196        """
197        self._test_running = False
198        """
199        **(bool):** True if a self-test is currently being run.
200        False otherwise.
201        """
202        self._test_ECD = None
203        """
204        **(str):** Estimated completion time of the running SMART selftest.
205        Not provided by SAS/SCSI devices.
206        """
207        self._test_progress = None
208        """
209        **(int):** Estimate progress percantage of the running SMART selftest.
210        """
211        self.diagnostics: Diagnostics = Diagnostics()
212        """
213        **Diagnostics** Contains parsed and processed diagnostic information
214        extracted from the SMART information. Currently only populated for
215        SAS and SCSI devices, since ATA/SATA SMART attributes are manufacturer
216        proprietary.
217        """
218        self.temperature: Optional[int] = None
219        """
220        **(int or None): Since SCSI disks do not report attributes like ATA ones
221        we need to grep/regex the shit outta the normal "smartctl -a" output.
222        In case the device have more than one temperature sensor the first value
223        will be stored here too.
224        Note: Temperatures are always in Celsius (if possible).
225        """
226        self.temperatures: Dict[int, int] = {}
227        """
228        **(dict of int): NVMe disks usually report multiple temperatures, which
229        will be stored here if available. Keys are sensor numbers as reported in
230        output data.
231        Note: Temperatures are always in Celsius (if possible).
232        """
233        self.logical_sector_size: Optional[int] = None
234        """
235        **(int):** The logical sector size of the device (or LBA).
236        """
237        self.physical_sector_size: Optional[int] = None
238        """
239        **(int):** The physical sector size of the device.
240        """
241        self.if_attributes: Union[None, NvmeAttributes] = None
242        """
243        **(NvmeAttributes):** This object may vary for each device interface attributes.
244        It will store all data obtained from smartctl
245        """
246
247        if self.name is None:
248            warnings.warn(
249                "\nDevice '{0}' does not exist! This object should be destroyed.".format(
250                    name)
251            )
252            return
253        # If no interface type was provided, scan for the device
254        # Lets do this only for the non-abridged case
255        # (we can work with no interface for abridged case)
256        elif self._interface is None and not self.abridged:
257            logger.trace(
258                "Determining interface of disk: {0}".format(self.name))
259            raw, returncode = self.smartctl.generic_call(
260                ['-d', 'test', self.dev_reference])
261
262            if len(raw) > 0:
263                # I do not like this parsing logic but it works for now!
264                # just for reference _stdout.split('\n') gets us
265                # something like
266                # [
267                #     ...copyright string...,
268                #     '',
269                #     "/dev/ada2: Device of type 'atacam' [ATA] detected",
270                #     "/dev/ada2: Device of type 'atacam' [ATA] opened",
271                #     ''
272                # ]
273                # The above example should be enough for anyone to understand the line below
274                try:
275                    for line in reversed(raw):
276                        if "opened" in line:
277                            self._interface = line.split("'")[1]
278
279                            if self._interface == "nvme":  # if nvme set SMART to true
280                                self.smart_capable = True
281                                self.smart_enabled = True
282
283                            break
284                except:
285                    # for whatever reason we could not get the interface type
286                    # we should mark this as an `abbridged` case and move on
287                    self._interface = None
288                    self.abbridged = True
289                # TODO: Uncomment the classify call if we ever find out that we need it
290                # Disambiguate the generic interface to a specific type
291                # self._classify()
292            else:
293                warnings.warn(
294                    "\nDevice '{0}' does not exist! This object should be destroyed.".format(
295                        name)
296                )
297                return
298        # If a valid device was detected, populate its information
299        # OR if in unabridged mode, then do it even without interface info
300        if self._interface is not None or self.abridged:
301            self.update()

Instantiates and initializes the pySMART.Device.

name: str

(str): Device's hardware ID, without the '/dev/' prefix. (ie: sda (Linux), pd0 (Windows))

family: Optional[str]

(str): Device's family (if any).

model: Optional[str]

(str): Device's model number (if any).

serial: Optional[str]

(str): Device's serial number (if any).

firmware: Optional[str]

(str): Device's firmware version.

smart_capable: bool

(bool): True if the device has SMART Support Available. False otherwise. This is useful for VMs amongst other things.

smart_enabled: bool

(bool): True if the device supports SMART (or SCSI equivalent) and has the feature set enabled. False otherwise.

assessment: Optional[str]

(str): SMART health self-assessment as reported by the device.

messages: List[str]

(list of str): Contains any SMART warnings or other error messages reported by the device (ie: ascq codes).

is_ssd: bool

(bool): True if this device is a Solid State Drive. False otherwise.

rotation_rate: Optional[int]

(int): The Roatation Rate of the Drive if it is not a SSD. The Metric is RPM.

attributes: List[Optional[pySMART.Attribute]]

(list of Attribute): Contains the complete SMART table information for this device, as provided by smartctl. Indexed by attribute #, values are set to 'None' for attributes not suported by this device.

test_capabilities

*(dict): * This dictionary contains key == 'Test Name' and value == 'True/False' of self-tests that this device is capable of.

tests: List[pySMART.TestEntry]

(list of TestEntry): Contains the complete SMART self-test log for this device, as provided by smartctl.

diagnostics: pySMART.diagnostics.Diagnostics

Diagnostics Contains parsed and processed diagnostic information extracted from the SMART information. Currently only populated for SAS and SCSI devices, since ATA/SATA SMART attributes are manufacturer proprietary.

temperature: Optional[int]

**(int or None): Since SCSI disks do not report attributes like ATA ones we need to grep/regex the shit outta the normal "smartctl -a" output. In case the device have more than one temperature sensor the first value will be stored here too. Note: Temperatures are always in Celsius (if possible).

temperatures: Dict[int, int]

**(dict of int): NVMe disks usually report multiple temperatures, which will be stored here if available. Keys are sensor numbers as reported in output data. Note: Temperatures are always in Celsius (if possible).

logical_sector_size: Optional[int]

(int): The logical sector size of the device (or LBA).

physical_sector_size: Optional[int]

(int): The physical sector size of the device.

if_attributes: Optional[pySMART.interface.nvme.NvmeAttributes]

(NvmeAttributes): This object may vary for each device interface attributes. It will store all data obtained from smartctl

dev_interface: Optional[str]

Returns the internal interface type of the device. It may not be the same as the interface type as used by smartctl.

Returns: str: The interface type of the device. (example: ata, scsi, nvme) None if the interface type could not be determined.

smartctl_interface: Optional[str]

Returns the interface type of the device as it is used in smartctl.

Returns: str: The interface type of the device. (example: ata, scsi, nvme) None if the interface type could not be determined.

interface: Optional[str]

Returns the interface type of the device as it is used in smartctl.

Returns: str: The interface type of the device. (example: ata, scsi, nvme) None if the interface type could not be determined.

dev_reference: str

The reference to the device as provided by smartctl.

  • On unix-like systems, this is the path to the device. (example /dev/)
  • On MacOS, this is the name of the device. (example )
  • On Windows, this is the drive letter of the device. (example )

Returns: str: The reference to the device as provided by smartctl.

vendor: Optional[str]

Returns the vendor of the device.

Returns: str: The vendor of the device.

capacity: Optional[str]

Returns the capacity in the raw smartctl format. This may be deprecated in the future and its only retained for compatibility.

Returns: str: The capacity in the raw smartctl format

diags: Dict[str, str]

Gets the old/deprecated version of SCSI/SAS diags atribute.

size_raw: Optional[str]

Returns the capacity in the raw smartctl format.

Returns: str: The capacity in the raw smartctl format

size: int

Returns the capacity in bytes

Returns: int: The capacity in bytes

sector_size: int

Returns the sector size of the device.

Returns: int: The sector size of the device in Bytes. If undefined, we'll assume 512B

def smart_toggle(self, action: str) -> Tuple[bool, List[str]]:
487    def smart_toggle(self, action: str) -> Tuple[bool, List[str]]:
488        """
489        A basic function to enable/disable SMART on device.
490
491        # Args:
492        * **action (str):** Can be either 'on'(for enabling) or 'off'(for disabling).
493
494        # Returns"
495        * **(bool):** Return True (if action succeded) else False
496        * **(List[str]):** None if option succeded else contains the error message.
497        """
498        # Lets make the action verb all lower case
499        if self._interface == 'nvme':
500            return False, ['NVME devices do not currently support toggling SMART enabled']
501        action_lower = action.lower()
502        if action_lower not in ['on', 'off']:
503            return False, ['Unsupported action {0}'.format(action)]
504        # Now lets check if the device's smart enabled status is already that of what
505        # the supplied action is intending it to be. If so then just return successfully
506        if self.smart_enabled:
507            if action_lower == 'on':
508                return True, []
509        else:
510            if action_lower == 'off':
511                return True, []
512        if self._interface is not None:
513            raw, returncode = self.smartctl.generic_call(
514                ['-s', action_lower, '-d', self._interface, self.dev_reference])
515        else:
516            raw, returncode = self.smartctl.generic_call(
517                ['-s', action_lower, self.dev_reference])
518
519        if returncode != 0:
520            return False, raw
521        # if everything worked out so far lets perform an update() and check the result
522        self.update()
523        if action_lower == 'off' and self.smart_enabled:
524            return False, ['Failed to turn SMART off.']
525        if action_lower == 'on' and not self.smart_enabled:
526            return False, ['Failed to turn SMART on.']
527        return True, []

A basic function to enable/disable SMART on device.

Args:

  • action (str): Can be either 'on'(for enabling) or 'off'(for disabling).

Returns"

  • (bool): Return True (if action succeded) else False
  • (List[str]): None if option succeded else contains the error message.
def all_attributes(self, print_fn=<built-in function print>):
529    def all_attributes(self, print_fn=print):
530        """
531        Prints the entire SMART attribute table, in a format similar to
532        the output of smartctl.
533        allows usage of custom print function via parameter print_fn by default uses print
534        """
535        header_printed = False
536        for attr in self.attributes:
537            if attr is not None:
538                if not header_printed:
539                    print_fn("{0:>3} {1:24}{2:4}{3:4}{4:4}{5:9}{6:8}{7:12}{8}"
540                             .format('ID#', 'ATTRIBUTE_NAME', 'CUR', 'WST', 'THR', 'TYPE', 'UPDATED', 'WHEN_FAIL',
541                                     'RAW'))
542                    header_printed = True
543                print_fn(attr)
544        if not header_printed:
545            print_fn('This device does not support SMART attributes.')

Prints the entire SMART attribute table, in a format similar to the output of smartctl. allows usage of custom print function via parameter print_fn by default uses print

def all_selftests(self):
547    def all_selftests(self):
548        """
549        Prints the entire SMART self-test log, in a format similar to
550        the output of smartctl.
551        """
552        if self.tests:
553            all_tests = []
554            if smartctl_type(self._interface) == 'scsi':
555                header = "{0:3}{1:17}{2:23}{3:7}{4:14}{5:15}".format(
556                    'ID',
557                    'Test Description',
558                    'Status',
559                    'Hours',
560                    '1st_Error@LBA',
561                    '[SK  ASC  ASCQ]'
562                )
563            else:
564                header = ("{0:3}{1:17}{2:30}{3:5}{4:7}{5:17}".format(
565                    'ID',
566                    'Test_Description',
567                    'Status',
568                    'Left',
569                    'Hours',
570                    '1st_Error@LBA'))
571            all_tests.append(header)
572            for test in self.tests:
573                all_tests.append(str(test))
574
575            return all_tests
576        else:
577            no_tests = 'No self-tests have been logged for this device.'
578            return no_tests

Prints the entire SMART self-test log, in a format similar to the output of smartctl.

def get_selftest_result(self, output=None):
664    def get_selftest_result(self, output=None):
665        """
666        Refreshes a device's `pySMART.device.Device.tests` attribute to obtain
667        the latest test results. If a new test result is obtained, its content
668        is returned.
669
670        # Args:
671        * **output (str, optional):** If set to 'str', the string
672        representation of the most recent test result will be returned, instead
673        of a `Test_Entry` object.
674
675        # Returns:
676        * **(int):** Return status code. One of the following:
677            * 0 - Success. Object (or optionally, string rep) is attached.
678            * 1 - Self-test in progress. Must wait for it to finish.
679            * 2 - No new test results.
680            * 3 - The Self-test was Aborted by host
681        * **(`Test_Entry` or str):** Most recent `Test_Entry` object (or
682        optionally it's string representation) if new data exists.  Status
683        message string on failure.
684        * **(int):** Estimate progress percantage of the running SMART selftest, if known.
685        Otherwise 'None'.
686        """
687        # SCSI self-test logs hold 20 entries while ATA logs hold 21
688        if smartctl_type(self._interface) == 'scsi':
689            maxlog = 20
690        else:
691            maxlog = 21
692        # If we looked only at the most recent test result we could be fooled
693        # by two short tests run close together (within the same hour)
694        # appearing identical. Comparing the length of the log adds some
695        # confidence until it maxes, as above. Comparing the least-recent test
696        # result greatly diminishes the chances that two sets of two tests each
697        # were run within an hour of themselves, but with 16-17 other tests run
698        # in between them.
699        if self.tests:
700            _first_entry = self.tests[0]
701            _len = len(self.tests)
702            _last_entry = self.tests[_len - 1]
703        else:
704            _len = 0
705        self.update()
706        # Since I have changed the update() parsing to DTRT to pickup currently
707        # running selftests we can now purely rely on that for self._test_running
708        # Thus check for that variable first and return if it is True with appropos message.
709        if self._test_running is True:
710            return 1, 'Self-test in progress. Please wait.', self._test_progress
711        # Check whether the list got longer (ie: new entry)
712        # If so return the newest test result
713        # If not, because it's max size already, check for new entries
714        if (
715                (len(self.tests) != _len) or
716                (
717                    len == maxlog and
718                    (
719                        _first_entry.type != self.tests[0].type or
720                        _first_entry.hours != self.tests[0].hours or
721                        _last_entry.type != self.tests[len(self.tests) - 1].type or
722                        _last_entry.hours != self.tests[len(
723                            self.tests) - 1].hours
724                    )
725                )
726        ):
727            return (
728                0 if 'Aborted' not in self.tests[0].status else 3,
729                str(self.tests[0]) if output == 'str' else self.tests[0],
730                None
731            )
732        else:
733            return 2, 'No new self-test results found.', None

Refreshes a device's pySMART.Device.tests attribute to obtain the latest test results. If a new test result is obtained, its content is returned.

Args:

  • output (str, optional): If set to 'str', the string representation of the most recent test result will be returned, instead of a Test_Entry object.

Returns:

  • (int): Return status code. One of the following:
    • 0 - Success. Object (or optionally, string rep) is attached.
    • 1 - Self-test in progress. Must wait for it to finish.
    • 2 - No new test results.
    • 3 - The Self-test was Aborted by host
  • (Test_Entry or str): Most recent Test_Entry object (or optionally it's string representation) if new data exists. Status message string on failure.
  • (int): Estimate progress percantage of the running SMART selftest, if known. Otherwise 'None'.
def abort_selftest(self):
735    def abort_selftest(self):
736        """
737        Aborts non-captive SMART Self Tests.   Note that this command
738        will  abort the Offline Immediate Test routine only if your disk
739        has the "Abort Offline collection upon new command"  capability.
740
741        # Args: Nothing (just aborts directly)
742
743        # Returns:
744        * **(int):** The returncode of calling `smartctl -X device_path`
745        """
746        return self.smartctl.test_stop(smartctl_type(self._interface), self.dev_reference)

Aborts non-captive SMART Self Tests. Note that this command will abort the Offline Immediate Test routine only if your disk has the "Abort Offline collection upon new command" capability.

Args: Nothing (just aborts directly)

Returns:

  • (int): The returncode of calling smartctl -X device_path
def run_selftest(self, test_type, ETA_type='date'):
748    def run_selftest(self, test_type, ETA_type='date'):
749        """
750        Instructs a device to begin a SMART self-test. All tests are run in
751        'offline' / 'background' mode, allowing normal use of the device while
752        it is being tested.
753
754        # Args:
755        * **test_type (str):** The type of test to run. Accepts the following
756        (not case sensitive):
757            * **short** - Brief electo-mechanical functionality check.
758            Generally takes 2 minutes or less.
759            * **long** - Thorough electro-mechanical functionality check,
760            including complete recording media scan. Generally takes several
761            hours.
762            * **conveyance** - Brief test used to identify damage incurred in
763            shipping. Generally takes 5 minutes or less. **This test is not
764            supported by SAS or SCSI devices.**
765            * **offline** - Runs SMART Immediate Offline Test. The effects of
766            this test are visible only in that it updates the SMART Attribute
767            values, and if errors are found they will appear in the SMART error
768            log, visible with the '-l error' option to smartctl. **This test is
769            not supported by SAS or SCSI devices in pySMART use cli smartctl for
770            running 'offline' selftest (runs in foreground) on scsi devices.**
771            * **ETA_type** - Format to return the estimated completion time/date
772            in. Default is 'date'. One could otherwise specidy 'seconds'.
773            Again only for ATA devices.
774
775        # Returns:
776        * **(int):** Return status code.  One of the following:
777            * 0 - Self-test initiated successfully
778            * 1 - Previous self-test running. Must wait for it to finish.
779            * 2 - Unknown or unsupported (by the device) test type requested.
780            * 3 - Unspecified smartctl error. Self-test not initiated.
781        * **(str):** Return status message.
782        * **(str)/(float):** Estimated self-test completion time if a test is started.
783        The optional argument of 'ETA_type' (see above) controls the return type.
784        if 'ETA_type' == 'date' then a date string is returned else seconds(float)
785        is returned.
786        Note: The self-test completion time can only be obtained for ata devices.
787        Otherwise 'None'.
788        """
789        # Lets call get_selftest_result() here since it does an update() and
790        # checks for an existing selftest is running or not, this way the user
791        # can issue a test from the cli and this can still pick that up
792        # Also note that we do not need to obtain the results from this as the
793        # data is already stored in the Device class object's variables
794        self.get_selftest_result()
795        if self._test_running:
796            return 1, 'Self-test in progress. Please wait.', self._test_ECD
797        test_type = test_type.lower()
798        interface = smartctl_type(self._interface)
799        try:
800            if not self.test_capabilities[test_type]:
801                return (
802                    2,
803                    "Device {0} does not support the '{1}' test ".format(
804                        self.name, test_type),
805                    None
806                )
807        except KeyError:
808            return 2, "Unknown test type '{0}' requested.".format(test_type), None
809
810        raw, rc = self.smartctl.test_start(
811            interface, test_type, self.dev_reference)
812        _success = False
813        _running = False
814        for line in raw:
815            if 'has begun' in line:
816                _success = True
817                self._test_running = True
818            if 'aborting current test' in line:
819                _running = True
820                try:
821                    self._test_progress = 100 - \
822                        int(line.split('(')[-1].split('%')[0])
823                except ValueError:
824                    pass
825
826            if _success and 'complete after' in line:
827                self._test_ECD = line[25:].rstrip()
828                if ETA_type == 'seconds':
829                    self._test_ECD = mktime(
830                        strptime(self._test_ECD, '%a %b %d %H:%M:%S %Y')) - time()
831                self._test_progress = 0
832        if _success:
833            return 0, 'Self-test started successfully', self._test_ECD
834        else:
835            if _running:
836                return 1, 'Self-test already in progress. Please wait.', self._test_ECD
837            else:
838                return 3, 'Unspecified Error. Self-test not started.', None

Instructs a device to begin a SMART self-test. All tests are run in 'offline' / 'background' mode, allowing normal use of the device while it is being tested.

Args:

  • test_type (str): The type of test to run. Accepts the following (not case sensitive):
    • short - Brief electo-mechanical functionality check. Generally takes 2 minutes or less.
    • long - Thorough electro-mechanical functionality check, including complete recording media scan. Generally takes several hours.
    • conveyance - Brief test used to identify damage incurred in shipping. Generally takes 5 minutes or less. This test is not supported by SAS or SCSI devices.
    • offline - Runs SMART Immediate Offline Test. The effects of this test are visible only in that it updates the SMART Attribute values, and if errors are found they will appear in the SMART error log, visible with the '-l error' option to smartctl. This test is not supported by SAS or SCSI devices in pySMART use cli smartctl for running 'offline' selftest (runs in foreground) on scsi devices.
    • ETA_type - Format to return the estimated completion time/date in. Default is 'date'. One could otherwise specidy 'seconds'. Again only for ATA devices.

Returns:

  • (int): Return status code. One of the following:
    • 0 - Self-test initiated successfully
    • 1 - Previous self-test running. Must wait for it to finish.
    • 2 - Unknown or unsupported (by the device) test type requested.
    • 3 - Unspecified smartctl error. Self-test not initiated.
  • (str): Return status message.
  • (str)/(float): Estimated self-test completion time if a test is started. The optional argument of 'ETA_type' (see above) controls the return type. if 'ETA_type' == 'date' then a date string is returned else seconds(float) is returned. Note: The self-test completion time can only be obtained for ata devices. Otherwise 'None'.
def run_selftest_and_wait(self, test_type, output=None, polling=5, progress_handler=None):
840    def run_selftest_and_wait(self, test_type, output=None, polling=5, progress_handler=None):
841        """
842        This is essentially a wrapper around run_selftest() such that we
843        call self.run_selftest() and wait on the running selftest till
844        it finished before returning.
845        The above holds true for all pySMART supported tests with the
846        exception of the 'offline' test (ATA only) as it immediately
847        returns, since the entire test only affects the smart error log
848        (if any errors found) and updates the SMART attributes. Other
849        than that it is not visibile anywhere else, so we start it and
850        simply return.
851        # Args:
852        * **test_type (str):** The type of test to run. Accepts the following
853        (not case sensitive):
854            * **short** - Brief electo-mechanical functionality check.
855            Generally takes 2 minutes or less.
856            * **long** - Thorough electro-mechanical functionality check,
857            including complete recording media scan. Generally takes several
858            hours.
859            * **conveyance** - Brief test used to identify damage incurred in
860            shipping. Generally takes 5 minutes or less. **This test is not
861            supported by SAS or SCSI devices.**
862            * **offline** - Runs SMART Immediate Offline Test. The effects of
863            this test are visible only in that it updates the SMART Attribute
864            values, and if errors are found they will appear in the SMART error
865            log, visible with the '-l error' option to smartctl. **This test is
866            not supported by SAS or SCSI devices in pySMART use cli smartctl for
867            running 'offline' selftest (runs in foreground) on scsi devices.**
868        * **output (str, optional):** If set to 'str', the string
869            representation of the most recent test result will be returned,
870            instead of a `Test_Entry` object.
871        * **polling (int, default=5):** The time duration to sleep for between
872            checking for test_results and progress.
873        * **progress_handler (function, optional):** This if provided is called
874            with self._test_progress as the supplied argument everytime a poll to
875            check the status of the selftest is done.
876        # Returns:
877        * **(int):** Return status code.  One of the following:
878            * 0 - Self-test executed and finished successfully
879            * 1 - Previous self-test running. Must wait for it to finish.
880            * 2 - Unknown or illegal test type requested.
881            * 3 - The Self-test was Aborted by host
882            * 4 - Unspecified smartctl error. Self-test not initiated.
883        * **(`Test_Entry` or str):** Most recent `Test_Entry` object (or
884        optionally it's string representation) if new data exists.  Status
885        message string on failure.
886        """
887        test_initiation_result = self.run_selftest(test_type)
888        if test_initiation_result[0] != 0:
889            return test_initiation_result[:2]
890        if test_type == 'offline':
891            self._test_running = False
892        # if not then the test initiated correctly and we can start the polling.
893        # For now default 'polling' value is 5 seconds if not specified by the user
894
895        # Do an initial check, for good measure.
896        # In the probably impossible case that self._test_running is instantly False...
897        selftest_results = self.get_selftest_result(output=output)
898        while self._test_running:
899            if selftest_results[0] != 1:
900                # the selftest is run and finished lets return with the results
901                break
902            # Otherwise see if we are provided with the progress_handler to update progress
903            if progress_handler is not None:
904                progress_handler(
905                    selftest_results[2] if selftest_results[2] is not None else 50)
906            # Now sleep 'polling' seconds before checking the progress again
907            sleep(polling)
908
909            # Check after the sleep to ensure we return the right result, and not an old one.
910            selftest_results = self.get_selftest_result(output=output)
911
912        # Now if (selftes_results[0] == 2) i.e No new selftest (because the same
913        # selftest was run twice within the last hour) but we know for a fact that
914        # we just ran a new selftest then just return the latest entry in self.tests
915        if selftest_results[0] == 2:
916            selftest_return_value = 0 if 'Aborted' not in self.tests[0].status else 3
917            return selftest_return_value, str(self.tests[0]) if output == 'str' else self.tests[0]
918        return selftest_results[:2]

This is essentially a wrapper around run_selftest() such that we call self.run_selftest() and wait on the running selftest till it finished before returning. The above holds true for all pySMART supported tests with the exception of the 'offline' test (ATA only) as it immediately returns, since the entire test only affects the smart error log (if any errors found) and updates the SMART attributes. Other than that it is not visibile anywhere else, so we start it and simply return.

Args:

  • test_type (str): The type of test to run. Accepts the following (not case sensitive):
    • short - Brief electo-mechanical functionality check. Generally takes 2 minutes or less.
    • long - Thorough electro-mechanical functionality check, including complete recording media scan. Generally takes several hours.
    • conveyance - Brief test used to identify damage incurred in shipping. Generally takes 5 minutes or less. This test is not supported by SAS or SCSI devices.
    • offline - Runs SMART Immediate Offline Test. The effects of this test are visible only in that it updates the SMART Attribute values, and if errors are found they will appear in the SMART error log, visible with the '-l error' option to smartctl. This test is not supported by SAS or SCSI devices in pySMART use cli smartctl for running 'offline' selftest (runs in foreground) on scsi devices.
  • output (str, optional): If set to 'str', the string representation of the most recent test result will be returned, instead of a Test_Entry object.
  • polling (int, default=5): The time duration to sleep for between checking for test_results and progress.
  • progress_handler (function, optional): This if provided is called with self._test_progress as the supplied argument everytime a poll to check the status of the selftest is done.

    Returns:

  • (int): Return status code. One of the following:

    • 0 - Self-test executed and finished successfully
    • 1 - Previous self-test running. Must wait for it to finish.
    • 2 - Unknown or illegal test type requested.
    • 3 - The Self-test was Aborted by host
    • 4 - Unspecified smartctl error. Self-test not initiated.
  • (Test_Entry or str): Most recent Test_Entry object (or optionally it's string representation) if new data exists. Status message string on failure.
def update(self):
 920    def update(self):
 921        """
 922        Queries for device information using smartctl and updates all
 923        class members, including the SMART attribute table and self-test log.
 924        Can be called at any time to refresh the `pySMART.device.Device`
 925        object's data content.
 926        """
 927        # set temperature back to None so that if update() is called more than once
 928        # any logic that relies on self.temperature to be None to rescan it works.it
 929        self.temperature = None
 930        # same for temperatures
 931        self.temperatures = {}
 932        if self.abridged:
 933            interface = None
 934            raw = self.smartctl.info(self.dev_reference)
 935
 936        else:
 937            interface = smartctl_type(self._interface)
 938            raw = self.smartctl.all(
 939                self.dev_reference, interface)
 940
 941        parse_self_tests = False
 942        parse_running_test = False
 943        parse_ascq = False
 944        message = ''
 945        self.tests = []
 946        self._test_running = False
 947        self._test_progress = None
 948        # Lets skip the first couple of non-useful lines
 949        _stdout = raw[4:]
 950
 951        #######################################
 952        #           Encoding fixing           #
 953        #######################################
 954        # In some scenarios, smartctl returns some lines with a different/strange encoding
 955        # This is a workaround to fix that
 956        for i, line in enumerate(_stdout):
 957            # character ' ' (U+202F) should be removed
 958            _stdout[i] = line.replace('\u202f', '')
 959
 960        #######################################
 961        #   Dedicated interface attributes    #
 962        #######################################
 963
 964        if interface == 'nvme':
 965            self.if_attributes = NvmeAttributes(iter(_stdout))
 966
 967            # Get Tests
 968            for test in self.if_attributes.tests:
 969                self.tests.append(TestEntry('nvme', test.num, test.description, test.status, test.powerOnHours,
 970                                  test.failingLBA, nsid=test.nsid, sct=test.sct, code=test.code, remain=100-test.progress))
 971
 972            # Set running test
 973            if any(test.status == 'Running' for test in self.if_attributes.tests):
 974                self._test_running = True
 975                self._test_progress = self.if_attributes.tests[0].progress
 976            else:
 977                self._test_running = False
 978                self._test_progress = None
 979
 980        else:
 981            self.if_attributes = None
 982
 983        #######################################
 984        #    Global / generic  attributes     #
 985        #######################################
 986        stdout_iter = iter(_stdout)
 987        for line in stdout_iter:
 988            if line.strip() == '':  # Blank line stops sub-captures
 989                if parse_self_tests is True:
 990                    parse_self_tests = False
 991                if parse_ascq:
 992                    parse_ascq = False
 993                    self.messages.append(message)
 994            if parse_ascq:
 995                message += ' ' + line.lstrip().rstrip()
 996            if parse_self_tests:
 997                # Detect Test Format
 998
 999                ## SCSI/SAS FORMAT ##
1000                # Example smartctl output
1001                # SMART Self-test log
1002                # Num  Test              Status                 segment  LifeTime  LBA_first_err [SK ASC ASQ]
1003                #      Description                              number   (hours)
1004                # # 1  Background short  Completed                   -   33124                 - [-   -    -]
1005                format_scsi = re.compile(
1006                    r'^[#\s]*(\d+)\s{2,}(.*[^\s])\s{2,}(.*[^\s])\s{2,}(.*[^\s])\s{2,}(.*[^\s])\s{2,}(.*[^\s])\s+\[([^\s]+)\s+([^\s]+)\s+([^\s]+)\]$').match(line)
1007
1008                ## ATA FORMAT ##
1009                # Example smartctl output:
1010                # SMART Self-test log structure revision number 1
1011                # Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
1012                # # 1  Extended offline    Completed without error       00%     46660         -
1013                format_ata = re.compile(
1014                    r'^[#\s]*(\d+)\s{2,}(.*[^\s])\s{2,}(.*[^\s])\s{1,}(.*[^\s])\s{2,}(.*[^\s])\s{2,}(.*[^\s])$').match(line)
1015
1016                if format_scsi is not None:
1017                    format = 'scsi'
1018                    parsed = format_scsi.groups()
1019                    num = int(parsed[0])
1020                    test_type = parsed[1]
1021                    status = parsed[2]
1022                    segment = parsed[3]
1023                    hours = parsed[4]
1024                    lba = parsed[5]
1025                    sense = parsed[6]
1026                    asc = parsed[7]
1027                    ascq = parsed[8]
1028                    self.tests.append(TestEntry(
1029                        format,
1030                        num,
1031                        test_type,
1032                        status,
1033                        hours,
1034                        lba,
1035                        segment=segment,
1036                        sense=sense,
1037                        asc=asc,
1038                        ascq=ascq
1039                    ))
1040                elif format_ata is not None:
1041                    ## ATA FORMAT ##
1042                    format = 'ata'
1043                    parsed = format_ata.groups()
1044                    num = parsed[0]
1045                    test_type = parsed[1]
1046                    status = parsed[2]
1047                    remain = parsed[3]
1048                    hours = parsed[4]
1049                    lba = parsed[5]
1050
1051                    try:
1052                        num = int(num)
1053                    except:
1054                        num = None
1055
1056                    self.tests.append(
1057                        TestEntry(format, num, test_type, status,
1058                                  hours, lba, remain=remain)
1059                    )
1060                else:
1061                    pass
1062
1063            # Basic device information parsing
1064            if any_in(line, 'Device Model', 'Product', 'Model Number'):
1065                self.model = line.split(':')[1].lstrip().rstrip()
1066                self._guess_smart_type(line.lower())
1067                continue
1068
1069            if 'Model Family' in line:
1070                self.family = line.split(':')[1].strip()
1071                self._guess_smart_type(line.lower())
1072                continue
1073
1074            if 'LU WWN' in line:
1075                self._guess_smart_type(line.lower())
1076                continue
1077
1078            if any_in(line, 'Serial Number', 'Serial number'):
1079                try:
1080                    self.serial = line.split(':')[1].split()[0].rstrip()
1081                except IndexError:
1082                    # Serial reported empty
1083                    self.serial = ""
1084                continue
1085
1086            vendor = re.compile(r'^Vendor:\s+(\w+)').match(line)
1087            if vendor is not None:
1088                self._vendor = vendor.groups()[0]
1089
1090            if any_in(line, 'Firmware Version', 'Revision'):
1091                self.firmware = line.split(':')[1].strip()
1092
1093            if any_in(line, 'User Capacity', 'Total NVM Capacity', 'Namespace 1 Size/Capacity'):
1094                # TODO: support for multiple NVMe namespaces
1095                m = re.match(
1096                    r'.*:\s+([\d,. \u2019\u00a0]+)\s\D*\[?([^\]]+)?\]?', line.strip())
1097
1098                if m is not None:
1099                    tmp = m.groups()
1100                    self._capacity = int(
1101                        tmp[0].strip().replace(',', '').replace('.', '').replace(' ', '').replace('\u2019', '').replace('\u00a0', ''))
1102
1103                    if len(tmp) == 2 and tmp[1] is not None:
1104                        self._capacity_human = tmp[1].strip().replace(',', '.')
1105
1106            if 'SMART support' in line:
1107                # self.smart_capable = 'Available' in line
1108                # self.smart_enabled = 'Enabled' in line
1109                # Since this line repeats twice the above method is flawed
1110                # Lets try the following instead, it is a bit redundant but
1111                # more robust.
1112                if any_in(line, 'Unavailable', 'device lacks SMART capability'):
1113                    self.smart_capable = False
1114                    self.smart_enabled = False
1115                elif 'Enabled' in line:
1116                    self.smart_enabled = True
1117                elif 'Disabled' in line:
1118                    self.smart_enabled = False
1119                elif any_in(line, 'Available', 'device has SMART capability'):
1120                    self.smart_capable = True
1121                continue
1122
1123            if 'does not support SMART' in line:
1124                self.smart_capable = False
1125                self.smart_enabled = False
1126                continue
1127
1128            if 'Rotation Rate' in line:
1129                if 'Solid State Device' in line:
1130                    self.is_ssd = True
1131                elif 'rpm' in line:
1132                    self.is_ssd = False
1133                    try:
1134                        self.rotation_rate = int(
1135                            line.split(':')[1].lstrip().rstrip()[:-4])
1136                    except ValueError:
1137                        # Cannot parse the RPM? Assigning None instead
1138                        self.rotation_rate = None
1139                continue
1140
1141            if 'SMART overall-health self-assessment' in line:  # ATA devices
1142                if line.split(':')[1].strip() == 'PASSED':
1143                    self.assessment = 'PASS'
1144                else:
1145                    self.assessment = 'FAIL'
1146                continue
1147
1148            if 'SMART Health Status' in line:  # SCSI devices
1149                if line.split(':')[1].strip() == 'OK':
1150                    self.assessment = 'PASS'
1151                else:
1152                    self.assessment = 'FAIL'
1153                    parse_ascq = True  # Set flag to capture status message
1154                    message = line.split(':')[1].lstrip().rstrip()
1155                continue
1156
1157            # Parse SMART test capabilities (ATA only)
1158            # Note: SCSI does not list this but and allows for only 'offline', 'short' and 'long'
1159            if 'SMART execute Offline immediate' in line:
1160                self.test_capabilities['offline'] = 'No' not in line
1161                continue
1162
1163            if 'Conveyance Self-test supported' in line:
1164                self.test_capabilities['conveyance'] = 'No' not in line
1165                continue
1166
1167            if 'Selective Self-test supported' in line:
1168                self.test_capabilities['selective'] = 'No' not in line
1169                continue
1170
1171            if 'Self-test supported' in line:
1172                self.test_capabilities['short'] = 'No' not in line
1173                self.test_capabilities['long'] = 'No' not in line
1174                continue
1175
1176            # Parse SMART test capabilities (NVMe only)
1177            if 'Optional Admin Commands' in line:
1178                if 'Self_Test' in line:
1179                    self.test_capabilities['short'] = True
1180                    self.test_capabilities['long'] = True
1181
1182            # SMART Attribute table parsing
1183            if 'Specific SMART Attributes' in line:
1184                attribute_re = re.compile(
1185                    r'^\s*(?P<id>\d+)\s+(?P<name>\S+)\s+(?P<flag>\S+)\s+(?P<value>\d+)\s+(?P<worst>\d+)\s+(?P<thresh>\S+)\s+(?P<type>\S+)\s+(?P<updated>\S+)\s+(?P<whenfailed>\S+)\s+(?P<raw>.+)$')
1186
1187                # loop until we reach the end of the table (empty line)
1188                while True:
1189                    line = next(stdout_iter).strip()
1190                    if line == '':
1191                        break
1192
1193                    # Parse the line
1194                    m = attribute_re.match(line)
1195                    if m is not None:
1196                        tmp = m.groupdict()
1197                        self.attributes[int(tmp['id'])] = Attribute(
1198                            int(tmp['id']), tmp['name'], int(tmp['flag'], base=16), tmp['value'], tmp['worst'], tmp['thresh'], tmp['type'], tmp['updated'], tmp['whenfailed'], tmp['raw'])
1199
1200            # For some reason smartctl does not show a currently running test
1201            # for 'ATA' in the Test log so I just have to catch it this way i guess!
1202            # For 'scsi' I still do it since it is the only place I get % remaining in scsi
1203            if 'Self-test execution status' in line:
1204                if 'progress' in line:
1205                    self._test_running = True
1206                    # for ATA the "%" remaining is on the next line
1207                    # thus set the parse_running_test flag and move on
1208                    parse_running_test = True
1209                elif '%' in line:
1210                    # for scsi the progress is on the same line
1211                    # so we can just parse it and move on
1212                    self._test_running = True
1213                    try:
1214                        self._test_progress = 100 - \
1215                            int(line.split('%')[0][-3:].strip())
1216                    except ValueError:
1217                        pass
1218                continue
1219            if parse_running_test is True:
1220                try:
1221                    self._test_progress = 100 - \
1222                        int(line.split('%')[0][-3:].strip())
1223                except ValueError:
1224                    pass
1225                parse_running_test = False
1226
1227            if "Self-test log" in line:
1228                parse_self_tests = True  # Set flag to capture test entries
1229                continue
1230
1231            #######################################
1232            #              SCSI only              #
1233            #######################################
1234            #
1235            # Everything from here on is parsing SCSI information that takes
1236            # the place of similar ATA SMART information
1237            if 'used endurance' in line:
1238                pct = int(line.split(':')[1].strip()[:-1])
1239                self.diagnostics.Life_Left = 100 - pct
1240                continue
1241
1242            if 'Specified cycle count' in line:
1243                self.diagnostics.Start_Stop_Spec = int(
1244                    line.split(':')[1].strip())
1245                continue
1246
1247            if 'Accumulated start-stop cycles' in line:
1248                self.diagnostics.Start_Stop_Cycles = int(
1249                    line.split(':')[1].strip())
1250                if self.diagnostics.Start_Stop_Spec and self.diagnostics.Start_Stop_Spec != 0:
1251                    self.diagnostics.Start_Stop_Pct_Left = int(round(
1252                        100 - (self.diagnostics.Start_Stop_Cycles /
1253                               self.diagnostics.Start_Stop_Spec), 0))
1254                continue
1255
1256            if 'Specified load-unload count' in line:
1257                self.diagnostics.Load_Cycle_Spec = int(
1258                    line.split(':')[1].strip())
1259                continue
1260
1261            if 'Accumulated load-unload cycles' in line:
1262                self.diagnostics.Load_Cycle_Count = int(
1263                    line.split(':')[1].strip())
1264                if self.diagnostics.Load_Cycle_Spec and self.diagnostics.Load_Cycle_Spec != 0:
1265                    self.diagnostics.Load_Cycle_Pct_Left = int(round(
1266                        100 - (self.diagnostics.Load_Cycle_Count /
1267                               self.diagnostics.Load_Cycle_Spec), 0))
1268                continue
1269
1270            if 'Elements in grown defect list' in line:
1271                self.diagnostics.Reallocated_Sector_Ct = int(
1272                    line.split(':')[1].strip())
1273                continue
1274
1275            if 'read:' in line:
1276                line_ = ' '.join(line.split()).split(' ')
1277                if line_[1] == '0' and line_[2] == '0' and line_[3] == '0' and line_[4] == '0':
1278                    self.diagnostics.Corrected_Reads = 0
1279                elif line_[4] == '0':
1280                    self.diagnostics.Corrected_Reads = int(
1281                        line_[1]) + int(line_[2]) + int(line_[3])
1282                else:
1283                    self.diagnostics.Corrected_Reads = int(line_[4])
1284                self.diagnostics._Reads_GB = float(line_[6].replace(',', '.'))
1285                self.diagnostics._Uncorrected_Reads = int(line_[7])
1286                continue
1287
1288            if 'write:' in line:
1289                line_ = ' '.join(line.split()).split(' ')
1290                if (line_[1] == '0' and line_[2] == '0' and
1291                        line_[3] == '0' and line_[4] == '0'):
1292                    self.diagnostics.Corrected_Writes = 0
1293                elif line_[4] == '0':
1294                    self.diagnostics.Corrected_Writes = int(
1295                        line_[1]) + int(line_[2]) + int(line_[3])
1296                else:
1297                    self.diagnostics.Corrected_Writes = int(line_[4])
1298                self.diagnostics._Writes_GB = float(line_[6].replace(',', '.'))
1299                self.diagnostics._Uncorrected_Writes = int(line_[7])
1300                continue
1301
1302            if 'verify:' in line:
1303                line_ = ' '.join(line.split()).split(' ')
1304                if (line_[1] == '0' and line_[2] == '0' and
1305                        line_[3] == '0' and line_[4] == '0'):
1306                    self.diagnostics.Corrected_Verifies = 0
1307                elif line_[4] == '0':
1308                    self.diagnostics.Corrected_Verifies = int(
1309                        line_[1]) + int(line_[2]) + int(line_[3])
1310                else:
1311                    self.diagnostics.Corrected_Verifies = int(line_[4])
1312                self.diagnostics._Verifies_GB = float(
1313                    line_[6].replace(',', '.'))
1314                self.diagnostics._Uncorrected_Verifies = int(line_[7])
1315                continue
1316
1317            if 'non-medium error count' in line:
1318                self.diagnostics.Non_Medium_Errors = int(
1319                    line.split(':')[1].strip())
1320                continue
1321
1322            if 'Accumulated power on time' in line:
1323                self.diagnostics.Power_On_Hours = int(
1324                    line.split(':')[1].split(' ')[1])
1325                continue
1326
1327            if 'Current Drive Temperature' in line or ('Temperature:' in
1328                                                       line and interface == 'nvme'):
1329                try:
1330                    self.temperature = int(
1331                        line.split(':')[-1].strip().split()[0])
1332
1333                    if 'fahrenheit' in line.lower():
1334                        self.temperature = int((self.temperature - 32) * 5 / 9)
1335
1336                except ValueError:
1337                    pass
1338
1339                continue
1340
1341            if 'Temperature Sensor ' in line:
1342                try:
1343                    match = re.search(
1344                        r'Temperature\sSensor\s([0-9]+):\s+(-?[0-9]+)', line)
1345                    if match:
1346                        (tempsensor_number_s, tempsensor_value_s) = match.group(1, 2)
1347                        tempsensor_number = int(tempsensor_number_s)
1348                        tempsensor_value = int(tempsensor_value_s)
1349
1350                        if 'fahrenheit' in line.lower():
1351                            tempsensor_value = int(
1352                                (tempsensor_value - 32) * 5 / 9)
1353
1354                        self.temperatures[tempsensor_number] = tempsensor_value
1355                        if self.temperature is None or tempsensor_number == 0:
1356                            self.temperature = tempsensor_value
1357                except ValueError:
1358                    pass
1359
1360                continue
1361
1362            #######################################
1363            #            Common values            #
1364            #######################################
1365
1366            # Sector sizes
1367            if 'Sector Sizes' in line:  # ATA
1368                m = re.match(
1369                    r'.* (\d+) bytes logical,\s*(\d+) bytes physical', line)
1370                if m:
1371                    self.logical_sector_size = int(m.group(1))
1372                    self.physical_sector_size = int(m.group(2))
1373                    # set diagnostics block size to physical sector size
1374                    self.diagnostics._block_size = self.physical_sector_size
1375                continue
1376            if 'Logical block size:' in line:  # SCSI 1/2
1377                self.logical_sector_size = int(
1378                    line.split(':')[1].strip().split(' ')[0])
1379                # set diagnostics block size to logical sector size
1380                self.diagnostics._block_size = self.logical_sector_size
1381                continue
1382            if 'Physical block size:' in line:  # SCSI 2/2
1383                self.physical_sector_size = int(
1384                    line.split(':')[1].strip().split(' ')[0])
1385                continue
1386            if 'Namespace 1 Formatted LBA Size' in line:  # NVMe
1387                # Note: we will assume that there is only one namespace
1388                self.logical_sector_size = int(
1389                    line.split(':')[1].strip().split(' ')[0])
1390                continue
1391
1392        if not self.abridged:
1393            if not interface == 'scsi':
1394                # Parse the SMART table for below-threshold attributes and create
1395                # corresponding warnings for non-SCSI disks
1396                self._make_smart_warnings()
1397            else:
1398                # If not obtained Power_On_Hours above, make a direct attempt to extract power on
1399                # hours from the background scan results log.
1400                if self.diagnostics.Power_On_Hours is None:
1401                    raw, returncode = self.smartctl.generic_call(
1402                        [
1403                            '-d',
1404                            'scsi',
1405                            '-l',
1406                            'background',
1407                            self.dev_reference
1408                        ])
1409
1410                    for line in raw:
1411                        if 'power on time' in line:
1412                            self.diagnostics.Power_On_Hours = int(
1413                                line.split(':')[1].split(' ')[1])
1414        # map temperature
1415        if self.temperature is None:
1416            # in this case the disk is probably ata
1417            try:
1418                # Some disks report temperature to attribute number 190 ('Airflow_Temperature_Cel')
1419                # see https://bugs.freenas.org/issues/20860
1420                temp_attr = self.attributes[194] or self.attributes[190]
1421                if temp_attr is not None and temp_attr.raw_int is not None:
1422                    self.temperature = temp_attr.raw_int
1423            except (ValueError, AttributeError):
1424                pass
1425        # Now that we have finished the update routine, if we did not find a runnning selftest
1426        # nuke the self._test_ECD and self._test_progress
1427        if self._test_running is False:
1428            self._test_ECD = None
1429            self._test_progress = None

Queries for device information using smartctl and updates all class members, including the SMART attribute table and self-test log. Can be called at any time to refresh the pySMART.Device object's data content.

def smart_health_assement( disk_name: str, interface: Optional[str] = None, smartctl: pySMART.smartctl.Smartctl = <pySMART.smartctl.Smartctl object>) -> Optional[str]:
49def smart_health_assement(disk_name: str, interface: Optional[str] = None, smartctl: Smartctl = SMARTCTL) -> Optional[str]:
50    """
51    This function gets the SMART Health Status of the disk (IF the disk
52    is SMART capable and smart is enabled on it else returns None).
53    This function is to be used only in abridged mode and not otherwise,
54    since in non-abridged mode update gets this information anyways.
55
56    Args:
57        disk_name (str): name of the disk
58        interface (str, optional): interface type of the disk (e.g. 'sata', 'scsi', 'nvme',... Defaults to None.)
59
60    Returns:
61        str: SMART Health Status of the disk. Returns None if the disk is not SMART capable or smart is not enabled on it.
62             Possible values are 'PASS', 'FAIL' or None.
63    """
64    assessment = None
65    raw = smartctl.health(os.path.join(
66        '/dev/', disk_name.replace('nvd', 'nvme')), interface)
67    line = raw[4]  # We only need this line
68    if 'SMART overall-health self-assessment' in line:  # ATA devices
69        if line.split(':')[1].strip() == 'PASSED':
70            assessment = 'PASS'
71        else:
72            assessment = 'FAIL'
73    if 'SMART Health Status' in line:  # SCSI devices
74        if line.split(':')[1].strip() == 'OK':
75            assessment = 'PASS'
76        else:
77            assessment = 'FAIL'
78    return assessment

This function gets the SMART Health Status of the disk (IF the disk is SMART capable and smart is enabled on it else returns None). This function is to be used only in abridged mode and not otherwise, since in non-abridged mode update gets this information anyways.

Args: disk_name (str): name of the disk interface (str, optional): interface type of the disk (e.g. 'sata', 'scsi', 'nvme',... Defaults to None.)

Returns: str: SMART Health Status of the disk. Returns None if the disk is not SMART capable or smart is not enabled on it. Possible values are 'PASS', 'FAIL' or None.