May 7, 2022

Creating Disk Image and MBR

Creating disk image or just MBR (master boot record) in Linux is common for backups, copying disks, and recovery. And the 'dd' command is an easy to use tool for making such clones.

To clone an entire hard disk:

# dd if=/dev/sda of=/dev/sdb bs=64K conv=noerror,sync

The cmdline above set the block size to 64k (can be 128k or other value), and continue operation and ignoring all read errors. It also add input blocks with zeroes if there were any read errors, so data offsets stay in sync. Both hard disks (sda and sdb) must be the same size.


To clone a partition and make a disk image:

dd if=/dev/sdb1 of=disk_sdb1.img bs=128K conv=noerror,sync

dd if=/dev/sdb1 conv=sync,noerror bs=128K | gzip -c > disk_sdb1.img.gz

dd if=/dev/sdb1 conv=sync,noerror bs=128K status=progress | gzip -c | ssh xx@remote.ip dd of=disk_sdb1.img.gz

 

To restore system:

# gunzip -c disk_sdb1.img.gz | dd of=/dev/sdb1


To copy MBR:

# dd if=/dev/sda of=/dev/sdb bs=512 count=1

The cmdline above will copy 512 bytes (MBR) from sda to sdb disk. This only work if both disks are identically sized partitions.

# dd if=/dev/sda of=/tmp/mbrsda.bak bs=512 count=1

The cmdline above will copy 512 bytes (MBR) from sda to a disk image for 2 disks with different size partitions.


To restore the MBR to any sdb:

# dd if=/tmp/mrbsda.bak of=/dev/sdb bs=446 count=1

Master Boot Record (MBR) is the 512-byte boot sector that is the first sector of a partitioned data storage device of a hard disk.  MBR is divided into 3 sections:
1. Bootstrap - 446 bytes
2. Partition table - 64 bytes
3. Signature - 2 bytes

For restore MBR, use 446 bytes to overwrite/restore your /dev/sda MBR boot code only, and use 512 bytes to overwrite/restore your /dev/sda full MBR.


To backup and restore the primary and extended partition tables:

# sfdisk -d /dev/sda > /tmp/sda.bak

# sfdisk /dev/sda < /tmp/sda.bak

 

To backup MBR and Extended Partitions schema:

# dd if=/dev/sda of=/tmp/backup-sda.mbr bs=512 count=1

# sfdisk -d /dev/sda > /tmp/backup-sda.sfdisk

 

To restore MBR and Extended Partition schema:

# dd if=/tmp/backup-sda.mbr of=/dev/sda

# sfdisk /dev/sda < /tmp/backup-sda.sfdisk

 

Links:

  • https://www.cyberciti.biz/faq/unix-linux-dd-create-make-disk-image-commands/
  • https://www.cyberciti.biz/faq/howto-copy-mbr/