Thursday, March 12, 2009

Die GPT die!

From time to time you move hard drive between systems that uses GPT by default (Solaris with ZFS, Apple MacOS etc) and system that don't (Windows, Linux, BSDs) you might get annoyed by your favourite partitioning tools in the later systems for not having GPT support. The solution? Kill the GPT signatures and continue to use your favourite tool!

Problem is that GPT records exists in both the beginning AND the end of a disk - so the usual dd if=/dev/zero of=/dev/yournewdisk count=100 trick won't work. Of course you can wipe the whole drive with dd - but that would be slow and unnecessary. So what to do? Python come to rescue! The following script will completely nuke your partition table on a given disk so that you can start from scratch - make sure you know what you are doing!



#!/usr/bin/env python
import sys

'''
Nuke GPT on any given block device.

lestercheung <<<<<<<<<>>>>>>>>> gmail.com
'''

def ftell_test(d):
f = open(d, "r")
f.seek(0, 2) # SEEK_END is 2
return f.tell()

def clear_gpt(target):
'''
According to http://en.wikipedia.org/wiki/GUID_Partition_Table - GPT
stores partition data in the first and last 34 LBA blocks. A LBA sector
is normally 512 bytes.
'''
fd = open(target, "w+")
fd.seek(0)
fd.write('\0' * 34 * 512)
print "done nuking data at the beginning of disk", target
fd.seek(0, 2) # SEEK_END is 2
disk_size = fd.tell()
fd.seek(disk_size - 34*512)
fd.write('\0' * 34 * 512)
print "done nuking data at the end of disk", target

if __name__ == '__main__':
for x in sys.argv[1:]:
#print ftell_test(x)
clear_gpt(x)

3 comments:

Mike said...

I have looked everywhere for a script to do this. Thank you so much!

Lester Cheung said...

Glad to hear that you find it useful. How did you find this? Search engine? What did you searched for?

Anonymous said...

Super useful, thanks!