fdisk -l
has got to be one of the more common disk-related commands one might use while fussing about with raw disk images. The fdisk utility is ubiquitous across linux distributions (also brew install gptfdisk
and brew cask install gdisk
, supposedly). The -l
argument provides a quick look raw sector & file system info. Figuring out the Start, End, Sectors, Size, Id, Format
of a disk image’s contents without needing to mount it and start lurking around is handy, just the sort of thing one might want to do with Python. Lets write a function to get these attributes into a dictionary- here’s mine:
import subprocess
import re
def fdisk(image):
# `image`, a .img disk image:
cmd = str('fdisk -l ' + image)
# read fdisk output- everything `cmd` would otherwise print to your console on stdout
# is instead piped into `proc`.
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
# the raw stuff from stdout is not parseable as is, so we read into a string:
result = proc.stdout.read().__str__()
# figure out what type we should iterate with when looking via file / part contained within image. I have no idea if anything besides .img will work- YMMV, but YOLO xD
if '.iso' in result:
iter = '.iso'
if '.qcow2' in result:
iter = '.qcow2'
else:
iter = '.img'
# chop up fdisk results by file / partition-
# the resulting `parts` are equivalent to fdisk "rows" in the shell
parts = re.findall(r'' + iter + r'\d', result)
# dictionary `disk` contains each "row" from `parts`:
disk = {}
for p in parts:
# sub dictionary 'part' contains the handy fdisk output values:
part = {}
# get just the number words with regex sauce:
line = result.split(p)[1]
words = re.split(r'\s+', line)
# place each word into 'part':
part['Start'] = words[1]
part['End'] = words[2]
part['Sectors'] = words[3]
part['Size'] = words[4]
part['Id'] = words[5]
part['Format'] = words[6].split('\\n')[0]
# stick this part into 'disk', move onto next disk part:
disk[p] = part
return disk
Leave a Reply