Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain detailed device / partition info from file path on Linux (like UUID, hard drive serial etc.)

Starting with an absolute file path, I want to obtain the following information:

  1. The mount point of the filesystem on which the file is stored (in order to compute the path relative to the mount point)
  2. The UUID and label of the file system
  3. The type (or vendor name) and the serial number of the hard drive that contains the partition

I am aware that 2 and 3 may be undefined in many cases (e.g. for loopback, ramfs, encyrpted devices), which is totally fine. I also know how to obtain that information using a shell and system tools like df and the /sys or /proc filesystem. See this question for reference.

However, I am searching for the least cumbersone method to do that programmatically with Python 3.5. That means:

  • Prefer system calls instead of parsing contents of /proc or /sys (which may be subject to change or depend on kernel configuration?)
  • Avoid calling subprocesses and parsing their output (the definition of cumbersome)

So far, I am using os.stat() on the path to get the block device's major and minor number from stat_result.st_dev. But what's the proper way to proceed?

There is for example

  • /proc/mounts
  • /proc/partitions
  • /sys/dev/block/<major>:<minor>

Notes: Regarding mounted block devices an partitions, /proc/mounts and /proc/partitions seem to be the canonical information source (which is OK). For UUIDs, labels, serials etc. I currently use udevadm and parse the output:

def get_udev_properties(dev_name):        
    cmd = ["udevadm", "info", "--query=property", "--name", dev_name]
    result = subprocess.run(cmd, stdout=subprocess.PIPE)
    return parse_properties(result.stdout)

Further note: Abstracting from my acutal problem, one could ask more general:

  • What's the canonical identification or representation of a block device with respect to linux system calls and the kernel filesystems?
  • What's the proper way to obtain that representation by major and minor number?
  • What's the proper way to obtain detailed information about a block device?
like image 365
code_onkel Avatar asked Jul 04 '16 13:07

code_onkel


Video Answer


1 Answers

This is a script on GitHub I came across earlier today that uses Python to fetch information about drive make and model (and lots of others).

/proc/partitions holds info on partitions; for more detailed information you'll have either to run a subprocess as you do now, or for example for GPT do the parsing yourself.

like image 138
LSerni Avatar answered Oct 28 '22 13:10

LSerni