问题
Starting with an absolute file path, I want to obtain the following information:
- The mount point of the filesystem on which the file is stored (in order to compute the path relative to the mount point)
- The UUID and label of the file system
- 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?
回答1:
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.
回答2:
The best way to do that is via pyparted
. Pyparted are python bindings to Parted maintained by one of the Parted developers. You can find the source code on github. Unfortunately UUID's cannot be found from parted so you have to parse blkid
回答3:
That would imply some utilities and anlyze output. Launched using os.popen, you can use bklkid
to find uuids, reading /etc/mtab
file permits to know which filesystem are mounted in your system and thus mountpoints. sfdisk -l
output gives you disk anatomy.hdparm -I /dev/xxx
will give you serial numbers.
来源:https://stackoverflow.com/questions/38185473/how-to-obtain-detailed-device-partition-info-from-file-path-on-linux-like-uui