Восстанавливаем загрузчик linux grub

Восстановление GRUB

GRUB — это основной загрузчик Ubuntu начиная с версии 9.10. Ранее он был известен как GRUB2 и пришёл он на смену старой версии GRUB, известной теперь как GRUB Legacy. Если вам необходимо восстановить GRUB Legacy, например поскольку у Вас стоит версия Ubuntu старше 9.10, то вам необходимо прочитать соответствующую статью.

Несмотря на то, что это фактически две версии одного приложения с названием GRUB, они не имеют ничего общего и являются совершенно разными программами.

На любом загрузочном винчестере есть так называемая Главная загрузочная запись (англ. master boot record, MBR), к которой обращается BIOS при загрузке компьютера. В эту область загрузчик системы и должен записать информацию об основных файлах, которые хранятся уже на разделах винчестера.

Каждый раз при установке или восстановлении систем от Microsoft загрузчики Linux заменяются и их необходимо заново устанавливать.

Восстановление с помощью LiveCD/USB

Первый способ

Запустите систему с LiveCD/USB и откройте терминал. Для этого можно нажать Alt + F2 и ввести команду:

Далее необходимо узнать Вашу таблицу разделов. Используйте команду:

На экран должна быть выведена примерно такая таблица:

/dev/sda3 239616 233392328 233152713 111,2G Microsoft basic data /dev/sda4 233394176 234438655 1044480 510M Windows recovery environment . Disk identifier: 0x7d6fe43d Device Boot Start End Sectors Size Id Type /dev/sdc1 * 2048 29304782 29302735 14G 83 Linux /dev/sdc2 29304832 1953523711 1924218880 917,6G 83 Linux

Из таблицы видим, что Linux (загрузочный /-корень отмечен звёздочкой) стоит, в нашем случае, на разделе /dev/sdc1.

Теперь подключим этот раздел в /mnt следующей командой (следим за пропусками между кодами и порядковыми номерами разделов):

Затем, для записи grub в MBR, вводите следующую команду:

sudo grub-install --root-directory=/mnt /dev/sdc

В случае, если нужно только восстановить MBR диска (например, после переустановки Windows), то этого достаточно, закрываем терминал и перезагружаем.

Если нужно обновить и меню grub (например, после установки Windows), то нужно сделать:

sudo update-grub --output=/mnt/boot/grub/grub.cfg

Восстановление используя chroot

Запустите систему с LiveCD/USB и откройте терминал. Для этого можно нажать Alt + F2 и ввести команду:

Далее необходимо узнать Вашу таблицу разделов. Используйте команду:

На экран должна быть выведена примерно такая таблица:

/dev/sda1 29 8369 66999082+ 83 Linux /dev/sda2 * 8370 13995 45190845 7 HPFS/NTFS /dev/sda3 13996 14593 4803435 5 Extended

Теперь нужно примонтировать Ваш Linux раздел (здесь это sda1) и еще несколько важных директорий:

sudo mount /dev/sda1 /mnt sudo mount --bind /dev /mnt/dev sudo mount --bind /proc /mnt/proc sudo mount --bind /sys /mnt/sys

Если раздел /boot или /var находится отдельно, то Вам необходимо примонтировать их в /mnt/boot и /mnt/var

Читайте также:  Linux disk performance test

Теперь перейдем в окружающую среду chroot:

Теперь необходимо установить GRUB, используя команду:

grub-install --recheck /dev/sda

Также в некоторых случаях может помочь вариант:

grub-install --recheck --no-floppy /dev/sda

Если все прошло успешно, выходим из chroot командой:

Теперь необходимо отмонтировать разделы:

sudo umount /mnt/dev sudo umount /mnt/proc sudo umount /mnt/sys sudo umount /mnt

Если Вы монтировали раздел /boot воспользуйтесь командой:

Затем перезагрузим Ваш компьютер командой:

При необходимости Вы можете обновить меню загрузчика командой:

Восстановление в rescue mode

При отсутствии загрузочного диска, можно восстановить Grub из его консоли. Восстановление происходит следующим образом: сначала нужно подгрузить все модули, чтобы стала доступна вся функциональность Grub, а затем уже запуститься с нужного раздела. Как известно, Grub состоит из двух частей. Первая часть записана в MBR диска. Она содержит базовую функциональность, то есть в ней есть консоль в rescue mode и ничего больше. Вначале нужно определить, на каком разделе находится вторая часть груба (она лежит в каталоге /boot/grub), подгрузить недостающие модули. И только потом можно будет дать команду запуска с нужного раздела. В rescue mode доступно всего четыре команды:

Вначале следует дать команду:

В ответ она выведет, например, следующее:

(hd0) (hd0,msdos3) (hd0,msdos2) (hd0,msdos1) (hd1) (hd1,msdos2) (hd1,msdos1)

Иногда Grub может неправильно опеределить, какие файловые системы находятся на разделах дисков. В данном случае определяет их как msdos. Нам нужно постараться угадать, какие диски мы видим. В данном случае видно два диска. Диск с индексом 0 содержит три раздела, диск с индексом 1 содержит два раздела. Зная структуру своих дисков несложно определить нужный диск.

Grub называет разделы в обратном порядке. И становится непонятно, что имеется в виду под (hd0,msdos3) — первый раздел или третий? Тут можно выкрутиться, использовав синтаксис (hd0,1). Нужно помнить, что в Grub счет дисков начинается с 0, а счет разделов — с 1. Предположим, что Линукс установлен на первый диск в первый раздел, то есть (hd0,1). Даем команду:

set prefix=(hd0,1)/boot/grub set root=(hd0,1)

Этими командами мы указываем использовать диск (hd0,1) для дальнейших команд. После чего нужно проверить, действительно ли на этом разделе есть то, что нам нужно. Даем команду:

если в ответ получаем список всех файлов в этой директории, то диск и раздел выбраны правильно. Подгружаем модули:

insmod ext2 insmod normal normal
set prefix=(hd0,1)/@/boot/grub set root=(hd0,1)
insmod btrfs insmod normal

После чего Grub перейдёт в полнофункциональный режим. Он автоматически найдет все операционки, которые можно подгружать, и покажет своё Grub-меню.

Дальнейшее восстановление сводится к тому, чтобы загрузить нужный нам Linux, и в нем от рута дать команду:

Где sdX, диск, на который нужно установить Grub.

Источник

How to Use Grub Rescue to Fix Linux Boot Failure

The GRUB (Grand Unified Bootloader) is a tool for booting and loading operating system kernels and the default bootloader for systems based on the Linux kernel. Although it runs first when a machine is turned on, regular users rarely see GRUB in action. It functions automatically and requires no user input.

Читайте также:  Перезагрузка сетевого интерфейса линукс

However, when attempting to boot another operating system alongside Linux on the same machine, the other system’s bootloader may overwrite GRUB, resulting in the inability of the Linux system to boot up.

This article will show you how to fix Linux boot failure using GRUB Rescue commands and the Boot Repair tool.

How to use Grub Rescue to fix Linux boot failure

Note: The tutorial below is written for GRUB 2, the current iteration of the GRUB bootloader.

GRUB Boot Issues

The most common reason for GRUB not booting into the operating system is another OS’s bootloader overwriting GRUB boot configuration. The problem occurs during an attempt a dual boot with an existing Linux installation. Another reason is the accidental removal of GRUB configuration files.

When GRUB is not able to boot the system, the GRUB Rescue prompt appears.

GRUB displaying

The example above shows GRUB displaying the «no such partition» error before displaying the grub rescue prompt. Another common GRUB error is «unknown filesystem», followed by the same prompt.

GRUB displaying

Sometimes, the screen may show the grub prompt only.

GRUB displaying only the GRUB prompt.

GRUB Rescue Commands

Below is the list of the commonly used GRUB Rescue commands. Use the commands in the prompts mentioned in the previous section.

Command Description Example
boot Start booting (shortcuts: F10, CTRL + x). The command is issued without arguments.
cat Write the contents of a file to standard output. cat (hd0,1)/boot/grub/grub.cfg
configfile Load a configuration file. configfile (hd0,1)/boot/grub/grub.cfg
initrd Load the initrd.img file. initrd (hd0,1)/initrd.img
insmod Load a module. insmod (hd0,1)/boot/grub/normal.mod
loopback Mount an image file as a device. loopback loop0 (hd0,1)/iso/image.iso
ls Display the contents of a directory or partition. ls (hd0,1)
lsmod Display a list of loaded modules. The command is issued without arguments.
normal Activate the normal module. The command is issued without arguments.
search Search for devices. Option —file searches for files, —label searches for labels, —fs-uuid searches for filesystem UUID. search -file [filename]
set Set an environment variable. If issued with no arguments, the command prints the list of all environment variables and their values. set [variable-name]=[value]

Fixing Boot Failure

This tutorial covers two ways to resolve GRUB boot issues, using the GRUB Rescue prompt, and the Boot Repair tool.

Via Grub Terminal

1. Use the set command with no arguments to view the environment variables:

The example output shows that GRUB is set up to boot from (hd0,msdos3) partition:

The output of the set command in GRUB.

2. The ls command lists the available partitions on the disk.

Читайте также:  Install virtualbox for kali linux

The output shows the partition list.

The output of the ls command in GRUB.

Use the ls command to find the partition containing the boot directory.

The example shows the boot directory in the (hd0,msdos1) partition.

Finding the partition containing the boot folder in GRUB.

3. Set the boot partition as the value of the root variable. The example uses the partition named (hd0,msdos1) .

4. Load the normal boot mode.

5. Start the normal boot mode.

The normal mode enables you to issue more complex commands.

6. Load the Linux kernel using the linux command.

linux /boot/vmlinuz-4.2.0-16-generic root=/dev/sda1 ro

7. Issue the boot command.

The system now boots properly.

Via Live image

Another way to fix your GRUB boot issues is to use a Linux live image to boot from an external device.

1. Download a live Linux installer. This example uses the Ubuntu 20.04 ISO image.

2. Use a tool such as Etcher to write the Linux image to an SD card or a USB flash drive.

3. Insert the bootable device and start the computer.

4. Select Try Ubuntu on the welcome screen.

The Ubuntu welcome screen.

5. When the live system boots up, connect to the internet.

6. Open the terminal and type the following command to add the repository for the Boot Repair tool.

sudo add-apt-repository ppa:yannubuntu/boot-repair

Adding the repository for the Boot Repair tool.

Press Enter and wait for the repository to be added.

7. Update the repositories.

8. Install the Boot Repair tool.

sudo apt install boot-repair

9. Start the Boot Repair tool via the terminal.

10. Select Recommended repair.

Selecting Recommended repair on the Boot Repair main screen.

Wait for the tool to finish repairing the bootloader.

Note: The Boot Repair tool is available as a live image, so you can boot it from an external drive without using another live OS.

Updating GRUB config file

When the system successfully boots up, make sure the GRUB configuration is up to date.

Updating GRUB in the Linux terminal.

Reinstalling GRUB

Follow the steps below to reinstall GRUB on your Linux system.

1. Mount the partition containing the OS installation. The example mounts the /dev/sda1 partition to the /mnt directory.

2. Bind the /dev , /dev/pts , /proc , and /sys directories to the corresponding directories in the /mnt folder.

sudo mount --bind /dev /mnt/dev && sudo mount --bind /dev/pts /mnt/dev/pts && sudo mount --bind /proc /mnt/proc && sudo mount --bind /sys /mnt/sys
sudo grub-install -root-directory=/mnt/ /dev/sda

Reinstalling GRUB in the Linux terminal.

4. Unmount the directories when the installation completes successfully.

sudo umount /mnt/sys && sudo umount /mnt/proc && sudo umount /mnt/dev/pts && sudo umount /mnt/dev && sudo umount /mnt

After reading this article, you should be able to fix your Linux boot failure using GRUB Rescue or Boot Repair utilities. For another way to fix your boot-related issues, read How to Use fsck Command.

Источник

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