Python 获取磁盘信息

一,使用 subprocess + shell 命令实现

二,使用 Psutil 实现 (用python实现系统相关的命令行功能)

 

一,使用 subprocess + shell 命令实现

# -*- coding=utf-8 -*-
# Created Time: 2016年12月16日 星期五 16时53分27秒
# File Name: 02_os_disk_info.py

"""
获取磁盘信息
"""

import subprocess


def get_one(path):

    # 指定单位 -BK -BM -BG
    df = subprocess.Popen(['df', '-BG', path], stdout=subprocess.PIPE)

    output = df.communicate()[0]

    print output

    device, size, used, available, percent, mountpoint = \
            output.split('\n')[1].split()

    print 'device: ', device
    print 'seize: ', size
    print 'used: ', used
    print 'available: ', available
    print 'percent: ', percent
    print 'mountpoint: ', mountpoint
    print '########################'


def get_all():

    # 指定单位 -BK -BM -BG
    df = subprocess.Popen(['df', '-BG'], stdout=subprocess.PIPE)

    output = df.communicate()[0]

    print output

    for i in xrange(30):

        try:
            device, size, used, available, percent, mountpoint = \
                    output.split('\n')[i+1].split()

            print '########################'
            print 'device: ', device
            print 'seize: ', size
            print 'used: ', used
            print 'available: ', available
            print 'percent: ', percent
            print 'mountpoint: ', mountpoint
        except:
            break


def main():

    path = '/dev/sda1'

    get_one(path)

    get_all()


if __name__ == '__main__':
    main()

输出:

$ python 02_os_disk_info.py 
Filesystem     1G-blocks  Used Available Use% Mounted on
/dev/sda1           902G   38G      819G   5% /

device:  /dev/sda1
seize:  902G
used:  38G
available:  819G
percent:  5%
mountpoint:  /
########################
df: /run/user/1000/gvfs: Transport endpoint is not connected
Filesystem     1G-blocks  Used Available Use% Mounted on
udev                  8G    1G        8G   1% /dev
tmpfs                 2G    1G        2G   1% /run
/dev/sda1           902G   38G      819G   5% /
none                  1G    0G        1G   0% /sys/fs/cgroup
none                  1G    0G        1G   0% /run/lock
none                  8G    1G        8G   3% /run/shm
none                  1G    1G        1G   1% /run/user

########################
device:  udev
seize:  8G
used:  1G
available:  8G
percent:  1%
mountpoint:  /dev
########################
device:  tmpfs
seize:  2G
used:  1G
available:  2G
percent:  1%
mountpoint:  /run
########################
..
..

 

二,使用 Psutil 实现

In [1]: import psutil

In [2]: partitions = psutil.disk_partitions()

In [3]: partitions
Out[3]: 
[sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,relatime,errors=remount-ro,data=ordered'),
 sdiskpart(device='/dev/sdb4', mountpoint='/media/bwhite/\\xc7\xd7\xb0\\xae\\xb5\\xc4-B4FE-5315', fstype='vfat', opts='rw,nosuid,nodev,noexec,relatime,uid=1000,fmask=0022,dmask=0022,codepage=936,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro')]

In [4]: foo = psutil.disk_usage(partitions[1].mountpoint)

In [5]: foo
Out[5]: sdiskusage(total=4015390720, used=1512292352, free=2503098368, percent=37.7)

In [6]: 

 

转载于:https://my.oschina.net/bwhite/blog/807313

<think>我们正在Debian系统中使用Python获取磁盘温度。根据引用[3]和引用[4],我们可以使用psutil库来获取硬件信息,但需要注意,psutil的sensors_temperatures()方法可以获取温度信息,但可能不包括磁盘温度。磁盘温度通常需要从硬盘的S.M.A.R.T.数据中读取。在Linux中,我们可以通过读取/sys文件系统或使用smartctl工具(来自smartmontools包)来获取磁盘温度。由于psutil可能无法直接提供磁盘温度,我们考虑以下两种方法:方法1:通过/sys文件系统读取在/sys/class/hwmon/目录下,有各个硬件监控设备的子目录。我们可以遍历这些目录,查找磁盘温度传感器。但这种方法比较复杂,因为不同硬件传感器的命名可能不同。方法2:使用smartctl工具安装smartmontools包,然后通过命令行调用smartctl获取磁盘温度,再用Python解析输出。由于方法2更为直接且可靠,我们选择使用smartctl。步骤:1.安装smartmontools:sudoapt-getinstallsmartmontools2.在Python调用smartctl命令并解析输出。注意:运行smartctl可能需要root权限。我们可以通过设置sudo规则来避免在脚本中使用root密码,或者让脚本以root权限运行。示例代码:我们可以使用subprocess模块来运行命令并获取输出。但是,请注意,用户要求使用Python获取磁盘温度。我们可以尝试使用一个现有的Python库来读取S.M.A.R.T.数据,比如`pySMART`。但为了减少依赖,我们也可以直接解析smartctl的输出。这里我们提供两种方式:方式一:使用subprocess直接调用smartctl方式二:使用pySMART库(如果用户愿意安装额外的库)由于用户没有指定必须使用某个库,我们先给出使用subprocess的示例,因为这样不需要额外安装Python库(除了系统已经安装的)。使用subprocess的示例代码:首先,确保已安装smartmontools。然后,编写Python代码:```pythonimportsubprocessdefget_disk_temperature(disk='/dev/sda'):try:#使用sudo运行smartctl命令,注意:可能需要配置sudoers以允许无密码运行cmd=['sudo','smartctl','-A',disk]output=subprocess.check_output(cmd,universal_newlines=True)#解析输出,查找温度行forlineinoutput.split('\n'):if'Temperature_Celsius'inline:#通常格式为:194Temperature_Celsius0x0000100100000Old_ageAlways-30parts=line.split()#温度值通常在最后几列,但更可靠的方式是找到第9列(从0开始计数,第10列?)#根据smartctl输出,温度值在倒数第二列(如果输出有10列,则索引为9)iflen(parts)>=10:try:temperature=int(parts[9])returntemperatureexcept(ValueError,IndexError):continuereturnNoneexceptsubprocess.CalledProcessErrorase:print(f"Errorrunningsmartctl:{e}")returnNone#示例:获取/dev/sda的温度temp=get_disk_temperature()iftempisnotNone:print(f"当前磁盘温度:{temp}°C")else:print("无法获取磁盘温度")```注意:上述代码假设磁盘设备为/dev/sda,并且smartctl输出中有一行包含字符串'Temperature_Celsius'。不同硬盘厂商的输出可能不同,例如可能是'Airflow_Temperature_Cel'或其他。因此,可能需要调整匹配的字符串。另外,需要确保用户有权限运行sudosmartctl。我们可以通过编辑sudoers文件(使用visudo)添加以下行来允许当前用户无密码运行smartctl:```usernameALL=(ALL)NOPASSWD:/usr/sbin/smartctl```其中username是运行脚本的用户。方式二:使用pySMART库首先安装pySMART:pipinstallpySMART然后使用以下代码:```pythonfrompySMARTimportDevicedefget_disk_temperature(disk='/dev/sda'):dev=Device(disk)#获取温度属性,具体属性名可能因磁盘而异#我们可以查找属性名为'Temperature'或'Temperature_Celsius'的属性forattrindev.attributes:ifattr.name=='Temperature'orattr.name=='Temperature_Celsius':returnattr.valuereturnNonetemp=get_disk_temperature()iftempisnotNone:print(f"当前磁盘温度:{temp}°C")else:print("无法获取磁盘温度")```注意:pySMART库同样需要调用smartctl,因此同样需要安装smartmontools,并且同样可能涉及权限问题。结论:在Debian系统中,我们可以通过安装smartmontools并使用Python调用smartctl或使用pySMART库来获取磁盘温度。根据引用[3]和引用[4],psutil库虽然可以获取温度,但主要是获取CPU温度等,对于磁盘温度,psutil的sensors_temperatures()通常不包括。因此,我们建议使用上述方法。另外,引用[3]中提到在安装psutil时可能会遇到缺少Python.h的问题,这需要安装python3-dev包(在Debian中)来解决。但这里我们并不需要psutil来获取磁盘温度。因此,推荐使用第一种方法(调用smartctl)或第二种方法(使用pySMART库)来获取磁盘温度。相关问题:1.如何在不使用sudo的情况下获取磁盘温度?2.除了磁盘温度,如何获取其他S.M.A.R.T.属性?3.在Windows系统中如何获取磁盘温度?4.如何监控多个磁盘的温度?5.如何定时获取磁盘温度并记录?</think>### Debian系统中使用Python获取磁盘温度的方法 在Debian系统中获取磁盘温度,推荐使用以下两种方法: #### 方法1:使用`smartmontools`工具(推荐) 这是最可靠的方式,通过Linux的S.M.A.R.T.监控系统获取硬盘数据。 1. **安装依赖**: ```bash sudo apt install smartmontools ``` 2. **Python代码示例**: ```python import subprocess def get_disk_temp(disk='/dev/sda'): try: cmd = f"sudo smartctl -A {disk} | grep 'Temperature_Celsius' | awk '{{print $10}}'" output = subprocess.check_output(cmd, shell=True, text=True) return int(output.strip()) except Exception as e: print(f"读取失败: {e}") return None # 使用示例 print(f"磁盘温度: {get_disk_temp()}°C") ``` #### 方法2:使用`hddtemp`工具 适用于快速获取温度,但兼容性不如smartmontools。 1. **安装工具**: ```bash sudo apt install hddtemp ``` 2. **Python代码**: ```python import subprocess def get_hdd_temp(): try: output = subprocess.check_output("sudo hddtemp /dev/sda", shell=True, text=True) return int(output.split(':')[-1].split()[0]) except Exception as e: print(f"错误: {e}") return None print(f"磁盘温度: {get_hdd_temp()}°C") ``` ### 注意事项 1. **权限问题**:两种方法都需要`sudo`权限,建议配置免密sudo或使用root运行 2. **设备路径**:根据实际磁盘路径修改`/dev/sda`(可用`lsblk`查看) 3. **温度字段**:不同硬盘厂商的S.M.A.R.T.字段名可能不同(如`Airflow_Temperature_Cel`) 4. **NVMe硬盘**:需使用`nvme smart-log /dev/nvme0`命令 > **替代方案**: > 虽然`psutil`库[^1][^4]能获取CPU温度,但**不支持磁盘温度**。如需完整硬件监控,可结合`pysmart`库(需先安装`smartmontools`): > ```bash > pip install pysmart > ``` > ```python > from pysmart.smart import Device > print(Device('/dev/sda').temperature) > ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值