How to read and restore the last megabyte of a drive using Python

I’m writing some code to do backups of my hard drives, using Python 3.

My issue is that some RAIDs and other things hide stuff in the first and/or last megabyte of some drives. I want to make sure I copy and restore any such things. The first megabyte is easy, but I’m unsure how best to do this for the last megabyte.

I see old threads about clearing the last 1MB, but the answers are mostly in shell. For example, see Wipe last 1MB of a Hard drive

But I want to read and restore it, and I want to use Python, so I could use some help.

Asked By: ForDummies

||

A block device, just like a regular file, has a size. You can query that, calculate the start of the last megabyte and seek there:

# assume you've already `open()`ed the file as f
# seek to end of file
f.seek(-2**20, os.SEEK_END)
last_MB_of_data = f.read()
backupfile = open("./end_backup", "wb")
backupfile.write(last_MB_of_data)
backupfile.close()

or similar.

However, of course, this, just as the start of the block device, of course are only the things that Linux sees; if the hardware hides the first or last MB from the operating system, this can’t circumvent that. Nothing could.

It’s pretty unusual to backup the first and last Megabyte separately – they’re useless without the stuff in between, and the stuff in between is useless without them. So, you’d basically always do a full-disk backup where you get these regions, anyways; or you’d do a backup of only the data-relevant parts (i.e., simply the relevant partitions, or really actually just the files as presented by the file system), and then these parts are irrelevant.

Answered By: Marcus Müller
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.