Fixing mbr in linux

How to Repair MBR (Windows Boot Loader) From Ubuntu

This simple tutorial shows you how to repair your Windows 7 boot loader (MBR) from Ubuntu dual boot or Ubuntu Live CD / USB. This can be useful if you don’t have a Windows CD or DVD on hand.

To do so, first boot into your Ubuntu system. When you’re in Ubuntu, press Ctrl+Alt+T on your keyboard to open terminal and follow below steps:

1.) First run below command to check your disk:

The output tells you the disk information:

Disk /dev/sda: 320.1 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders, total 625142448 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x016c8108

Device Boot Start End Blocks Id System
/dev/sda1 * 63 39054014 19526976 7 HPFS/NTFS/exFAT

2.) Now run commnad to install syslinux, which is a suite of lightweight IBM PC MBR bootloaders for starting up computers with the Linux kernel.

sudo apt-get update; sudo apt-get install syslinux

install syslinux to fix mbr

3.) Once installed, you can fix your Windows bootloader by running below command in terminal:

sudo dd if=/usr/lib/syslinux/mbr.bin of=/dev/sda

Replace the startup disk name /dev/sda in the above command according to the output in step 1.

repair-mbr

permalink

Ji m

I’m a freelance blogger who started using Ubuntu in 2007 and wishes to share my experiences and some useful tips with Ubuntu beginners and lovers. Please comment to remind me outdated tutorial! And, notify me if you find any typo/grammar/language mistakes. English is not my native language. Contact me via [email protected] Buy me a coffee: https://ko-fi.com/ubuntuhandbook1

19 responses to How to Repair MBR (Windows Boot Loader) From Ubuntu

THX Ji…
You saved me a lot of problems!! a bit more complicated in Windows 7 to resolve the MBR I know this is an older post but I do hope you will se this!!

Only output I got was: 0+1 records in
0+1 records out
440 bytes (440 B) copied, 0.0406588 s, 10.8 kB/s Is this right? If so, maybe the MBR wasn’t disrupted to begin with?

Источник

Восстановление убитых MBR и таблицы разделов

Ситуация следующая. Есть винт на 160Гб. На нем 2 раздела — 40Гб и 120Гб. С целью установки убунты как второй системы была произведена разбивка 120Гб -> 100+10+2+8.

Далее, с целью отката изменений, были объединены диски (10, 2 и 8) обратно в один 20Гб и отформатирован в NTFS. В нагрузку к этому, были проведены операции с MBR, результатом которой явилась ее смерть.

Итоги

1. При загрузке системы выводится сообщение MBR helper not found;
2. fdisk показывает один большой 160Гб диск.

Дураку понятно, что это начало веселой ночи.
Далее, под катом, решения вопроса.

1. Восстановление таблицы разделов

1.1. Parted magic

Данный LiveCD\USB дистрибутив, размером в 100Мб несет в себе огромную кучу софта, для работы с дисками. От разбивки, до восстановления.
Из них всех, нам нужны будут gpart, testdisk, fdisk и ms-sys.

Читайте также:  Linux servers with gui
1.2. Gpart

gpart — это утилита, сканирующая по-секторно диск на наличие разделов, которые присутствуют на носителе, но отсутствуют в таблице. В своей работе, она игнорирует уже существующую таблицу (если присутствует). Программа разаботана немецким программистом Michail Brzitwa и больше им не поддерживается. Вялотекущая разработка ведется командами Fedora и Debian. Текущая версия — 0.1h.

Утилита позволяет наиболее быстро и легко восстановить таблицу разделов, но она несет в себе несколько недостатков. Во-первых, разработка была давно заброшена, во-вторых, она иногда не совсем корректно определяет разделы.

gpart может работать в 2-х режимах. Это быстрый анализ и подробное сканирование. В некоторых случаях, первого режима достаточно. Мы же будем смотреть на второй.

gpart -if /dev/sda

-i — интерактивный режим. На каждую найденную партицию будет задан вопрос, сохранять ее, либо пропустить.
-f — полный скан диска.

После, довольно продолжительного времени, будет создан отчет с возможными разделами. Его-то и нужно обязательно максимально внимательно просмотреть перед записью.
Пример отчета (не мой):

Begin scan.
Possible partition(DOS FAT), size(1907mb), offset(0mb)
Possible partition(SGI XFS filesystem), size(5730mb), offset(1907mb)
End scan.
Checking partitions.
Partition(DOS or Windows 95 with 32 bit FAT, LBA): primary
Partition(Linux ext2 filesystem): primary
Ok.
Guessed primary partition table:
Primary partition(1)
type: 012(0x0C)(DOS or Windows 95 with 32 bit FAT, LBA)
size: 1907mb #s(3906544) s(16-3906559)
chs: (0/1/1)-(1023/19/16)d (0/1/1)-(12207/19/16)r
Primary partition(2)
type: 131(0x83)(Linux ext2 filesystem)
size: 5730mb #s(11736000) s(3906560-15642559)
chs: (1023/19/16)-(1023/19/16)d (12208/0/1)-(48882/19/16)r
Primary partition(3)
type: 000(0x00)(unused)
size: 0mb #s(0) s(0-0)
chs: (0/0/0)-(0/0/0)d (0/0/0)-(0/0/0)r
Primary partition(4)
type: 000(0x00)(unused)
size: 0mb #s(0) s(0-0)
chs: (0/0/0)-(0/0/0)d (0/0/0)-(0/0/0)r

Если все ОК, то соглашаемся на запись в таблицу разделов, скрещиваем пальцы и перезагружаемся.
В моем случае, программа определила разделы, которые были до разбивки (40 и 120), что не подходило и заставило искать альтернативные способы восстановления.

1.3. testdisk

Note: подробнее эта утилита описана в этом посте, здесь не буду повторяться.

Эта утилита аналогична предыдущей, но имеет ряд плюсов:
1. более свежая и активно поддерживается;
2. субъективно, работает намного быстрее;
3. функциональнее;
4. есть простой консольный интерфейс на базе ncurses.

Поехали!
1. в первом окне выбираем Create a new log file;
2. выбираем нужный диск (/dev/sda) -> Proceed;
3. отмечаем тип разделов как Intel;
4. выбираем Analyse current partition structure and search for lost partitions;
5. если найденные разделы верны, жмем Backup и переходим к пункту 6, есть возможность быстро пересканировать диск, если где-то ошибка (Quick search);
6. здесь уже виден зеленый список с разделами. Если ок, то записываем, иначе запускаем Deep search.;

В моем случае, результат был аналогичен результату gpart, что есть некорректен.
Запустив Deep search, выждав около 40 минут я получил ответ, от которого на душе так нехило отлегло.
Было найдено несколько партиций, которые накладывались одна на другую (это были изначальная (до манипуляций) 120Гб и новая, на 100Гб). Отметив ненужную, как удаленную, я записал таблицу на диск и перезагрузился. К счастью, все обошлось и компьютер вернулся к состоянию, который был изначально, а я мог с чистой совестью лечь спать.

3. Восстановление MBR

Для этой задачи, у нас в арсенале есть тулза ms-sys.
Сперва узнаем, что с нашей MBR.

ms-sys /dev/sda
/dev/sda has an x86 boot sector
it is unknown boot sector

Читайте также:  Система линукс нет звука

Теперь видно, что на данном диске нет загрузочного сектора.
Утилита может работать с MBR различных операционных систем. Список можно получить, запустив программу без агрументов. В моем случае, необходим был от Windows 7.
Записываем MBR на диск:

ms-sys -7 /dev/sda
Windows 7 master boot record successfully written to /dev/sda

Проверяем:

ms-sys /dev/sda
it is Microsof 7 master boot record, like the one this
program creates with the switch -7 on a hard disk device.

Вот и все, нужная MBR установлена и можно перезагружаться.

3. Outro

Этот пост пример того, как на пустом месте можно создать себе проблему и полночи заниматься не тем, чем надо. Но это дало неоценимый опыт, который я постарался изложить здесь.
Возможно, кому-нибудь он пригодится. Ведь в такую ситуацию попасть очень не сложно, а детального мануала особо-то и нет.

Источник

How to Repair a Corrupt MBR and boot into Linux

How to Repair a Corrupt MBR and boot into Linux

There are times when you inadvertently overwrite your Master Boot Record. The end result being that you are unable to boot into Linux. This is especially true when you are dual booting between windows and Linux OSes. Once when I was working in Windows XP, I accidentally clicked the hibernate button instead of shutdown. And windows somehow overwrote my MBR which housed the GRUB boot loader. At such times, it pays to have this cool tip at hand.
This is what you do to restore the GRUB boot loader when faced with the above problem. First you need a Linux distribution CD. If you are using Fedora (RedHat) then the first CD is sufficient. But you may also use any of the live CDs like Knoppix, Ubuntu Live CD and so on.

With Fedora CD

Boot your computer with the first CD of Fedora in your CD drive (You have to enable your PC to boot from the cdrom, which you can set in the BIOS settings). At the installation boot prompt that you get, enter the following command:
boot: linux rescue
… and press Enter. The installer will ask you a few questions like the language you would like to use, the type of keyboard etc. Then, if you have linux previously installed on your machine, the Fedora installer will automatically detect it and mount it in the /mnt/sysimage directory. Once the linux partition is mounted, you are dropped into the command shell prompt. The next step is to make your newly mounted directory the root (or parent) directory. This you do by running the chroot command as follows:
# chroot /mnt/sysimage
# _
Now you are in the shell with respect to the parent directory which is the linux partition on your harddisk.
From here, the steps needed depends on which bootloader you are using. You have to have a fair idea what is the device node of your harddisk partition housing your MBR. In most cases, it is /dev/hda if you have an IDE harddisk. But if you have a SCSI harddisk, it will be /dev/sda.

Restoring GRUB

Execute the following command:

# grub-install /dev/hda
… to install GRUB boot loader on to your MBR. And then type exit to reboot the machine. Now your GRUB boot loader is fixed.

Читайте также:  Touch screen linux debian

Restoring LILO

LILO stands for LInux LOader which was the boot loader used before GRUB was developed. It is fairly cryptic and is the default bootloader prior to and in RedHat 7.0 .
Here you just type the command:

# /sbin/lilo
… to install the bootloader on to the MBR.

If you don’t have a Fedora CD, then you need not despair. You can also repair the boot loader using one of the numerous live CDs available.

Using Knoppix CD to repair the boot loader

Here you have to boot into knoppix (either GUI mode or text mode). Once you are logged in, fire up a terminal (in GUI mode) and type the following commands:
$ su —
# fdisk -l

This will list your hard disk partition information. From the listing, you can know in which partition you have linux installed. Now you have to mount the partition which contains the linux filesystem. For the sake of this discussion, let us assume it is /dev/hda3 .
# mount -t ext3 -o rw /dev/hda3 /mnt
#_

Now your linux partition is mounted at /mnt . Next you have to use the chroot command as follows:
# chroot /mnt
#_

The rest of the steps are the same as listed above for Restoring GRUB and LILO boot loaders.

Update (August 01 2007): Many have said when they run the grub-install command after following the above steps, they get an error saying that /dev/hda is missing. The most probable reason is that when you chroot to the mount location, it does not have a copy of the device nodes on your machine. Here is a solution for that. If you have installed Linux with /boot, /usr and / in different partitions then the above method may not get the desired results and running the grub-install /dev/hda command after running chroot might give the error that there is no /dev/hda. This is because you have mounted only one of the partitions which houses ‘/’ . And the error tells you that it cannot find the device nodes. In this scenario you can do the following:

Lets say I have Linux installed with / in /dev/hda2, /boot in /dev/hda1 with an ext3 filesystem. I boot using a Live CD as described above and then mount the partitions as follows:

# mount -t ext3 /dev/hda2 /mnt
# mount -t ext3 /dev/hda1 /mnt/boot

Remember that you are mounting the boot partition into the boot directory inside /mnt. Now mount the proc filesystem of your liveCD as follows (This is really an optional step):

# mount -t proc none /mnt/proc
Finally bind the device nodes build by your liveCD to the /mnt/dev location as follows:

# mount -o bind /dev /mnt/dev
Now you can chroot to the /mnt location and run the grub-install command as described above.

# chroot /mnt
# grub-install /dev/hda

Please note: This updated method is applicable only if you have a Linux installation spread across multiple partitions. If you have installed Linux in a single partition, the first and second step works flawlessly.

Источник

Оцените статью
Adblock
detector