python udisks - enumerating device information

人走茶凉 提交于 2019-12-17 19:24:05

问题


It's apparently possible to get a lot of info relating to attached disks using the udisks binary:

udisks --show-info /dev/sda1

udisks is apparently just enumerating the data which is available udev.

Is it possible to get this information using python? say for example if i just wanted to retrieve the device serial, mount point and size.


回答1:


You can use Udisks via dbus directly in python.

import dbus

bus = dbus.SystemBus()
ud_manager_obj = bus.get_object("org.freedesktop.UDisks", "/org/freedesktop/UDisks")
ud_manager = dbus.Interface(ud_manager_obj, 'org.freedesktop.UDisks')

for dev in ud_manager.EnumerateDevices():
    device_obj = bus.get_object("org.freedesktop.UDisks", dev)
    device_props = dbus.Interface(device_obj, dbus.PROPERTIES_IFACE)
    print device_props.Get('org.freedesktop.UDisks.Device', "DriveVendor")
    print device_props.Get('org.freedesktop.UDisks.Device', "DeviceMountPaths")
    print device_props.Get('org.freedesktop.UDisks.Device', "DriveSerial")
    print device_props.Get('org.freedesktop.UDisks.Device', "PartitionSize")

The full list of properties available is here http://hal.freedesktop.org/docs/udisks/Device.html




回答2:


If all else fails you could parse the output of udisks. Here's an example script in Python3.2:

from subprocess import check_output as qx
from configparser import ConfigParser

def parse(text):
    parser = ConfigParser()
    parser.read_string("[DEFAULT]\n"+text)
    return parser['DEFAULT']

def udisks_info(device):
    # get udisks output
    out = qx(['udisks', '--show-info', device]).decode()

    # strip header & footer
    out = out[out.index('\n')+1:]
    i = out.find('=====')
    if i != -1: out = out[:i] 

    return parse(out)

info = udisks_info('/dev/sda1')
print("size = {:.2f} GiB".format(info.getint('size')/2**30))
print("""mount point = {mount paths}
uuid = {uuid}""".format_map(info))

# complex values could be parsed too
info = udisks_info('/dev/sda')
drive_data = info['drive'].replace('ports:\n', 'ports:\n  ')
print('serial =', parse(drive_data)['serial'])

Output

size = 57.15 GiB
mount point = /
uuid = b1812c6f-3ad6-40d5-94a6-1575b8ff02f0
serial = N31FNPH8


来源:https://stackoverflow.com/questions/5067005/python-udisks-enumerating-device-information

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!