使用pyudev获取硬盘序列号(USB闪存/ATA基础)

0 投票
1 回答
1852 浏览
提问于 2025-04-18 03:54

我一直在写下面这段示例代码,目的是用pyudev来获取连接的硬盘信息。

我想要检查的设备有:

  1. 普通的SATA硬盘
  2. USB转SATA转换器
  3. USB闪存盘

通过下面的脚本,我已经能够获取到USB闪存盘的信息。但是,当我连接USB转SATA转换器时,我得到的是转换器的序列号,而不是硬盘的序列号。此外,对于我的普通SATA硬盘,我在“ID_VENDOR”这一项上遇到了异常。

示例输出:

    Device Connected Info:
    [Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.1/2-1.1:1.0/host9/target9:0:0/9:0:0:0/block/sdc'), 
    Device(u'/sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/host7/target7:0:0/7:0:0:0/block/sdb'), 
    Device(u'/sys/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda')]

Device Information:
SonyPendrive:
{'model': u'Storage Media', 'vendor': u'Sony', 'serial': u'CB071031B7E215C294'}
SATA IDE Converter
{'model': u'DE SATA Device', 'vendor': u'USB TO I', 'serial': u'000000000033'}
Regular HDD
Traceback (most recent call last):
  File "t.py", line 52, in <module>
    devInfo=decode_device_info(deviceRef)
  File "t.py", line 9, in decode_device_info
    vendor = device['ID_VENDOR'].replace('_',' ')
  File "/home/srivathsan/Desktop/pyudev-pyudev-3a26e05/pyudev/device.py", line 831, in __getitem__
    raise KeyError(property)
KeyError: 'ID_VENDOR'

示例代码:

import glib
from pyudev import Context, Monitor

def decode_device_info(device):
    ''' Accept a device. Return a dict of attributes of given device.
    Clean up all strings in the process and make pretty.
    '''
    vendor = device['ID_VENDOR'].replace('_',' ')
    model = device['ID_MODEL'].replace('_',' ')
    try:
        serial = device['ID_SERIAL_SHORT']
    except:
        serial = device['ID_SERIAL']
    return({'vendor':vendor, 'model':model, 'serial':serial})

def getDevicelist(udevContext):
    devices=[]
    for device in udevContext.list_devices(subsystem='block', DEVTYPE='disk'):
        # Filter out cd drives, loop devices.
        if device.get('ID_TYPE', '') == 'cd':
            continue
        if device.get('UDISKS_PRESENTATION_NOPOLICY', '0') == '1':
            continue
        devices.append(device)
    return devices

try:
    from pyudev.glib import MonitorObserver

    def device_event(observer, device):
        print 'event {0} on device {1}'.format(device.action, device)
except:
    from pyudev.glib import GUDevMonitorObserver as MonitorObserver

    def device_event(observer, action, device):
        print 'event {0} on device {1}'.format(action, device)

context = Context()
monitor = Monitor.from_netlink(context)
monitor.filter_by(subsystem='block')
observer = MonitorObserver(monitor)
observer.connect('device-event', device_event)
monitor.start()

devicesConnected=getDevicelist(context)
if (devicesConnected):
    print devicesConnected
    for deviceRef in devicesConnected:
        devInfo=decode_device_info(deviceRef)
        print devInfo 

glib.MainLoop().run()

我是不是漏掉了什么参数?请给我一些建议。

1 个回答

0

对于你遇到的 KeyError 错误,你可以把

vendor = device['ID_VENDOR'].replace('_',' ')

替换成以下其中一个:

try:
    vendor = device['ID_VENDOR'].replace('_',' ')
except KeyError:
    vendor = ""

或者

vendor = device.get('ID_VENDOR', '').replace('_',' ')

或者

if 'ID_VENDOR' in device:
    vendor = device['ID_VENDOR'].replace('_',' ')
else:
    vendor = ""

不过,我不太确定你是否能用 pyudev 来获取连接在USB/SATA转换器后面的设备信息。

撰写回答