Restore the MBR of a Linux installation
As preparation for a restore test, I removed the master boot record (MBR) of a Linux system recently:
1# dd if=/dev/zero of=/dev/sda bs=512 count=1
This command fills the first 512 bytes (containing the partition table and bootloader) of the first hard drive (/dev/sda
) with zeroes (/dev/zero
).
The problem is when you discover that the restore did not work and you need to fix the system manually. 🙂
Procedure
To restore the MBR, a utility named testdisk
can be used. The program scans hard drives for known file system footprints and thus detects partition boundaries. The most Linux, Unix and Windows file systems can be detected.
Because the broken system is not capable of booting anymore, it is recommended to use a live medium - e.g. GParted, which already comes with the testdisk
utility.
After booting, a terminal is opened. As gparted
is not able to detect any partitions, it is necessary to utillize the lsscsi
and fdisk
commands, to find the correct hard drive:
Afterwards, testdisk
can be used to detect partitions and rewrite the MBR:
- Start
testdisk
and select a log file for documenting changes - Choose a hard drive and select Proceed
- Select the hard disk type: Intel should be select for conventional PCs with MBR/BIOS. Make sure to select EFI GPT for (U)EFI or GPT systems
- Select Analyse and Quick Search. If partitions were detect, you can select the menu item Write to rewrite the MBR:
Now, fdisk
also lists defined partitions again:
1# fdisk -l /dev/sda
2Disk /dev/sda: 21.5 GB, 21474836480 bytes
3255 heads, 63 sectors/track, 2610 cylinders
4Units = cylinders of 16065 * 512 = 8225280 bytes
5Sector size (logical/physical): 512 bytes / 512 bytes
6I/O size (minimum/optimal): 512 bytes / 512 bytes
7Disk identifier: 0x00000000
8
9 Device Boot Start End Blocks Id System
10/dev/sda1 * 1 64 512000 83 Linux
11/dev/sda2 64 2611 20458496 8e Linux LVM
If you would reboot the system right now, the boot would fail because of a missing bootloader. Depending on your configuration, you might need to re-install GRUB(2) - e.g. using the live medium:
1# mount /dev/sdaX /mnt
2# grub-install --no-floppy --root-directory=/mnt /dev/sda
It is getting tricky, if the GRUB version on the live medium is newer than the version on your host (GRUB2 vs. GRUB-legacy). In this case, pre-existing configuration files are incompatible and you need to mount all system partitions and use a chroot
environment:
1# mount /dev/sdaX /mnt
2# mount /dev/sdaX /mnt/boot
3...
4# mount --bind /dev /mnt/dev
5# mount --bind /tmp /mnt/tmp
6# mount -t proc proc /mnt/proc
7# mount -t sysfs none /mnt/sys
8# chroot /mnt /bin/bash
Now, the bootloader can be re-installed:
1# grep -v rootfs /proc/mounts > /etc/mtab
2# grub-install --no-floppy /dev/sda
The next boot should work like a charm again. 🙂