Sunday, 12 January 2014

Virtualize an old Windows XP disk partition (howto convert disk partition to virtual disk for VirtualBox)

I dug out an old hard disk. I was curious: what gems are stored here?

Turns out there was nothing, but it was in interesting exercise in converting a single disk partition into a VM - something that is not trivial.

I plugged my old drive into a USB hard disk docking station and had a look. It contained Windows XP and Linux from an old PC dating from 2004-2007 I believe.

"Hey!" I thought. I could virtualize this for no good reason and show how easy it is using free and open source software.

Ubuntu Packages

I installed VirtualBox and mbr.

Create VirtualBox VM

  • Select New
  • Name your VM (say TEST)
  • Select Windows and Windows XP
  • Set memory size (default is ok)
  • Select 'do not add a virtual hard drive' - we will create this later in tis VM's directory.

Create Virtual Disk Drive

Open a terminal and change to your ~/VirtualBox\ VM/TEST directory for this example.

Copy and paste my script into your editor.



printf "Copy boot sector image...\n"
sudo dd if=$DISK of=mbr.img bs=512 count=1 || { printf "FAILED\n"; exit 1; }
printf "Done\n"

# put 'normal' mbr incase grub or something was used
printf "Replace MBR code..."
sudo install-mbr mbr.img -t 36 || { printf "FAILED\n"; exit 1; }
printf "Done\n"

printf "Copy disk (%s) partition %d...(at 10MB/s 1GB will take 100s)...\n" "$DISK" $PART
sudo dd if=${DISK}${PART} of=$PARTIMG bs=512 || { printf "FAILED\n"; exit 1; }
sudo chown $USER:$USER $PARTIMG
printf "Done\n"

printf "Make VirtualBox VMDK image with MBR...\n"
sudo VBoxManage internalcommands createrawvmdk -filename ./disk.vmdk -rawdisk $DISK -partitions $PART -mbr ./mbr.img || { printf "FAILED\n"; exit 1; }
# VB needs this owned by user
sudo chown $USER:$USER disk-pt.vmdk
printf "Done\n"

# switch to partition image and zero starting offset
# eg.
# from this: RW 8514387 FLAT "/dev/sdd" 63
# to this: RW 8514387 FLAT "/home/phil/Development/pc-part2disk/part1.img" 0
printf "Modify VMDK files to use disk partition image...\n"
sudo cat disk.vmdk | sed "s@\"$DISK.*@\"./$PARTIMG\" 0@" > diskimage.vmdk
sudo chown $USER:$USER diskimage.vmdk
printf "Done\n"

# remove VB vmdk that points to physical drive - no longer required
sudo rm disk.vmdk

exit 0
 Change DISK and PART to suit your case. This example uses disk /dev/sdd and partition 1.

Also, run chmod +x