Linux live cd with grub

GRUB всемогущий, или Делаем загрузочную флешку

Про сам grub, загрузочные флешки и особенно специальные утилиты для создания дисков написано уже не мало, но выглядят они узко направленными. Например только для создания флешки Windows 7, различные PEtoUSB, есть более универсальные как в этом топике. Куча утилит по сути устанавливают загрузчик grub, isolinux (реже BCDW или lilo, еще реже свой как Win7), и затем раскладывают предложенные ему файлы (Windows7,WindowsXP, Ubuntu и т.д.) по папкам. От сюда и требовательность к образам (как писали в комментариях к этому топику).

А между тем абсолютное большинство выложенных в интернете дисков (особенно USB) как раз и используют isolinux и grub, что мешает их просто объединять? да ничего!

Я постараюсь с примерами рассказать, как сделать загрузочную, установочную и просто Live флешку, причем все в одном без заточенных под конкретный дистрибутив утилит. И иметь возможность, при необходимости, легко добавить на флешку еще что-то, без очередного ее переформатирования.

(С) Картинка оттуда

Демонстрация

Для пользователей Linux нет необходимости объяснять, как пользоваться командой grub-install /dev/sdb, да и преимущества grub им очевидны. Предвидя комментарии типа dd, хочу сказать, что статья нацелена в первую очередь на Windows пользователей.
Пользователям Windows я постараюсь объяснить преимущества grub, и надеюсь смогу убедить, что grub нужно держать если не первым, то вторым загрузчиком точно (флешку с grub иметь точно необходимо).
Для начала можно попробовать без затирания MBR. Достаточно прописать grub в boot.ini:
Нам понадобятся файлы из архива GRUB4DOS, копируем их в корень C:\, не обязательно что бы это был FAT, у меня работает и на NTFS:
default
grldr
grldr.mbr
menu.lst

Для Windows XP в boot.ini добавляем c:\grldr=»GRUB4DOS» . Все.
Либо запустить GRUB\install.bat из файла в приложении (файл install.bat взят из установщика xPUD ©, и только добавляет grub, ничего не копирует).

Для пользователей Vista и 7 установка несколько сложнее, чем в XP — делается это чрез bcdedit:

делаем резервную копию
bcdedit.exe /export «C:\BCD.bak»
bcdedit.exe /create /d «GRUB4DOS» /application bootsector
запоминаем GUID вида «<1a5b5afd-0469-110d-9a85-000103005000>«, и далее заменяем в команде GUID на эту строку

bcdedit.exe /set GUID device boot
bcdedit.exe /set GUID device partition=%SYSTEMDRIVE%
bcdedit.exe /set GUID path \grldr.mbr
bcdedit.exe /displayorder GUID /addlast

Либо так же запустить GRUB\install.bat из файла в приложении.

В общем то на этом установка закончена, и можно уже перезагружаться и поиграться с командной строкой (нажать С после появления меню grub).

Например, можно начать загрузку с дисковода:
chainloader (fd0)+1
rootnoverify (fd0)
boot

С привода компакт дисков:
cdrom —init
map —hook
chainloader (cd0)
boot

Выключить компьютер:
halt

Можно загрузиться с заранее вставленной флешки (если конечно там есть какой то загрузчик):
map (hd1) (hd0)
map (hd0) (hd1)
root (hd1,0)
chainloader +1
boot

А можно начать установку Windows 7, образ которой до этого просто разархивировали на флешку (и сама флешка не загрузочная):
root (hd1,0)
chainloader /bootmgr
boot

Напомню, что все это мы делали из режима командной строки. Но 1 в 1 (удалив только последнюю команду boot ), эти команды можно прописать и в menu.lst, и они будут работать из меню.

Случай из жизни: Cлетел MBR первого диска, и по этому BIOS загрузил сразу grub со второго диска. Увидев привычный синий экран, я смекнул что MBR, после очередных экспериментов, повреждена и требуется восстановление. Все что потребовалось мне, это перейти в режим командной строки ( С ) и ввести:
root (hd0,0)
chainloader /bootmgr
boot

И началась загрузка Windows7 После загрузки выполнил bootsect /nt60 c: /mbr И все (!)
Никакого безопасного режима или режима восстановления, ни каких 2-3 перезагрузок, и тем более ни каких дисков восстановления (да и нет у меня CD привода на нетбуке). После процедуры даже не понадобилось лишний раз перезагружаться, Windows загрузилась уже в штатном режиме (одно время я неделю ее так запускал, забывал восстановить MBR после загрузки).
Так же в архиве GRUB4DOS есть примеры автоматического поиска Windows XP и Windows 7/Vista, и даже если вы не знаете где у вас установлена Windows — все равно можно загрузиться при слетевшей MBR.

Установка

И так, Вы прониклись и хотите сделать себе такую флешку, но у Вас уже есть флешка на 16Гб и форматировать ее крайне не желательно, а большинство распространенных утилит (и инструкций) для изготовления бут-флешек предлагают ее предварительно отформатировать, что бы, полагаю, убедиться, что на создаваемой флешке точно файловая система FAT32. А потом устанавливают туда опять же grub или isolinux.

Установить grub можно без форматирования (при условии, конечно, что у вас уже FAT32, коих абсолютное большинство). Есть утилитка Winrub (любителям GUI), а в архиве GRUB4DOS есть bootlace.com. Рассмотрим вариант WinGrub. Раньше это был sfx архив, который сам себя распаковывает в %programfiles% и создавал ярлык на рабочем столе, что мне не нравилось. Достаточно было его самостоятельно распаковать, запустив потом grubinst_gui.exe. Когда писал статью, скачал последнюю версию, там уже инсталятор более менее полноценный. Качаем, ставим. Либо смотрим приложенный файл в конце статьи, я выложу свой комплект для сборки архивом. Запускаем, далее выбираем флешку (ориентируясь по размеру), и в partition list выбираем MBR или Whole disk. Жмем Install. Появляется окно консоли «The MBR/BS has been successfully installed«, с предложением нажать Enter, После нажатия которого — оно закрывается. В случае если написал «grubinst: Should be a disk image» поставьте галочку «Floppy image» и повторно нажмите Install

Теперь GRUB4DOS прописан в MBR.
После (хотя можно и ДО), копируем файлы из архива GRUB4DOS в корень флешки:
default
grldr
grldr.mbr
menu.lst
И редактируем menu.lst по желанию, параллельно наполняем флешку (часть пунктов уже можно посмотреть в статье выше, да и сам архив содержит примеры).

Наполняем

1. Alkid live
В полной раздаче есть архив multiboot.7z, где есть пример файла для grub, от туда его и возьмем, а сам ISO просто разархивируем в корень. Переименовываем i386 в minint, если забудем то не запустится, но скажет что не найден minint (что и стало столь не очевидной подсказкой).
Добавляем в menu.lst
title Alkid Live CD
root (hd0,0)
chainloader (hd0,0)/minint/setuplns.bin

В папке programs можно удалить лишнее, если флешка не сильно большая. А так же обновить базы антивирусов до актуального состояния.

Читайте также:  Windows 2012 код ошибки 0x80004005

2. Hiren’s BootCD
Открываем ISO и видим, что в папке HBCD лежит конфиг загрузчика isolinux.
Разархивируем папку HBCD в корень флешки, открываем isolinux.cfg:
menu label Start BootCD
kernel /HBCD/memdisk
append initrd=/HBCD/boot.gz

что легко преобразуется в синтаксис grub
title Start BootCD
root (hd0,0)
kernel /HBCD/memdisk
initrd /HBCD/boot.gz

добавляем и его в menu.lst
Установка закончена.

3. Некоторые мелкие утилиты уже есть готовые в интернете. обычно это образ дискеты с memtest, Ghost, DOS, PQMagic. Грузиться с них так же не составляет труда. Прописываем в menu.lst:
title Ghost 11
map —mem /Ghost.ima (fd0)
map —floppies=1
map —hook
chainloader (fd0)+1
rootnoverify (fd0)

У меня EEEPC без CD привода и когда вдруг встала необходимость восстановить его, я даже не задумался где взять внешний привод. Переписал Ghost образ с DVD дсика на флешку на «большом» компе, загрузился с флешки и восстановил.

4. Запуск дистрибутива. Возьмем для примера образ Parted Magic. Качаем образ для USB. Он уже на grub и имеет очень большое меню различных вариантов загрузки. Для его установки распаковываем архив, папка pmagic должна оказаться в корне, и из boot\grub файл menu.lst копируем в \pmagic, а в наш груб добавляем:
title PМagic
configfile /pmagic/menu.lst

Эта команда загрузит меню из родного menu.lst от pmagic, и нам не придется вообще ничего изобретать. Разве что добавить в \pmagic\menu.lst пункт для возврата обратно в наше:
title

В последней версии PМagic добавилась еще куча утилит, в т.ч. memtest, восстановление grub, hardware analyzer. Рекомендую самостоятельно потренироваться в «переселении» их на свою флешку, подглядывая в п.3 или menu.lst.

5. Запуск Live Ubuntu. У меня лежал «ubuntu-9.10-desktop-i386.iso«, на его примере и рассмотрим. Так же, разархивируем в корень. В папке isolinux (ее после можно удалить), в файле text.cfg находм как запускается Live режим, и соответственно добавляем свои строки в menu.lst (сравните что там было и что получилось)
title Try Ubuntu without any change to your computer
root (hd0,0)
kernel /casper/vmlinuz file=/preseed/ubuntu.seed boot=casper
initrd /casper/initrd.lz

6. Установка Debian (точно так же ставится и Ubuntu):
Для этого нам понадобится файлы HD-Media (или графический инсталятор) из репозитория, и ISO образ DVD1. Складываем все это в корень, а в grub добавляем:
title Debian Install
kernel /vmlinuz
init /initrd.gz

После начала установки будет найден образ ISO DVD1 и продолжится установка без сети, без CD приводов.

7. Установка на флешку Антивирусов сильно сложнее, например установку Dr.Web Live CD я расписывал тут.

Образы антивирусов не все удалось нормально «подселить» на флешку, если кто то сможет и поделится опытом буду рад (сам давно их не качал, возможно в последних версиях это уже делается сильно проще). В образе от Dr.Web, например, лежит даже инструкция по установке на флешки.
Для справки Live образы антивирусов:
Dr.Web
BitDefender
Avast! уже платный 🙁
Symantec NAV
Panda
Avira

8. DOS. Тут стоит разделить, если нам нужен ДОС для какой то серьезной работы, то имеет смысл найти DOS-Live образы, например этот, и грузить как в п.3. Мы же запускаем DOS что бы потом из него запустить установку Windows XP. От ДОСа нам понадобятся:
AUTOEXEC.BAT
COMMAND.COM
CONFIG.SYS
EMM386.EXE
HIMEM.SYS
IO.SYS
SMARTDRV.EXE

желательно, но не обязательно:
Mouse.com
MOUSE.INI
OAKCDROM.SYS

Копируем все это в корень флешки, а в menu.lst добавляем
title DOS (Install WinXP?)
root (hd0,0)
makeactive
chainloader /io.sys
Тут можно либо насладиться DOS, либо заранее в AUTOEXEC.BAT прописать (файл ответов конечно по желанию):
smartdrv
cd \WinXP\i386
winnt /U:\WinXP\i386\winnt.sif

9. Установка Windows 7. Как уже писал выше достаточно разархивировать ISO в корень флешки, а в menu.lst добавить (уже с hd0,0)
root (hd0,0)
chainloader /bootmgr
boot

10. Ну и для ровного счета расскажу еще об одном типе утилит. Некоторые (не все!) ISO образы могут быть загружены прямо из grub. Среди таких у меня нашлись: Acronis True Image, Acronis Disk Director, Active Password Changer. Это особым образом подготовленные образы (не простой слепок с CD), их загружать следующим образом:
title Active Password Changer
map (hd0,0)/Pwdchanger.iso (hd32)
map —hook
chainloader (hd32)

Удаление

Что делать если случайно установили grub в MBR основного диска, а не флешки, либо нужно удалить с флешки? Можно воспользоваться утилитой bootsect.exe как я писал выше.
В случае если еще не перезагрузились (если перезагрузились, то при помощи grub загрузите Windows, способом описанным выше), и запустите bootsect.exe
Для восстановления Windows XP bootsect /nt52 c: /mbr
Для восстановления Windows Vista/7 bootsect /nt60 c: /mbr
bootsect находится в папке boot диска Windows, а так же есть в моем выложенном архиве в конце статьи.
Флешку же достаточно просто отформатировать.

Заключение

Надеюсь что примеры помогут кому то разобраться, а кому то заинтересоваться данным загрузчиком, а утилиты для создания загрузочных флешек будут вызывать улыбку (ни кого не хочу обидеть, уважаю всех разработчиков, больше того сам с таких утилит начинал). Ну и конечно же очень рекомендую изучить подробнее сам grub, и GRUB4DOS, например вот русское руководство по последнему.
Перед добавлением очередного дистрибутива или утилитки, следите что бы папки не совпадали. Часть Linux дистрибутивов, при определенной сноровке и хорошем владении grub, позволяет безболезненно переименовать свою папку. Особенно не большие, на подобии pmagic, puppy, xpud.
В общем, не бойтесь экспериментировать, и удачи!

Так же ресурсы, которые могут быть полезны тем, кто хочет создать свою загрузочную флешку:
greenflash.su
flashboot.ru
lexapass.narod.ru

Приложение — мой архивчик со всем необходимым: bootsect, DOS, grub install скипт, WINGRUB, grub4dos. А так же список файлов на моей флешке c описаниями (некоторые просили).

UPD:

  • Форум где обсуждают варианты создания и загрузки ISO-образов.
  • В этой статье, от savvateev, он расказывается как решить некоторые возникающие проблемы, в том числе и фрагментацию образов ISO.
  • Статья «Программа для быстрого теста загрузочных дисков». С помощью описанной в статье утилиты загрузочную флешку можно тестировать мгновенно и без перезагрузки компьютера.
  • Скрипт для создания LiveLinux из любого дистрибутива.

Источник

Create a Custom Debian Live Environment (CD or USB) with Grub Only

Feb 8, 2018 Updated Mar 15, 2020

Warning : I have stopped updating this article in favor of a similar, but updated, guide .

These are steps that I used on an Ubuntu 18.04 LTS (Bionic Beaver) 64-bit system to build an x86 Debian 9 (Stretch) live environment that I can boot from CD or USB.

Читайте также:  Не пингуется по имени только по ip linux

These steps can be used to create a live environment that is BIOS bootable (MBR), UEFI bootable (GPT), or combination of both UEFI and BIOS bootable. Something unique about this guide is that Syslinux/Isolinux are not used. Only Grub boot equipment. This is done for consistency and to avoid mixing the two (Syslinux/Isolinux alone cannot accomplish everything covered in this article, but Grub can).

Here are some alternatives to my guide that may be better solutions for anyone reading this article: live-build , mkusb, UNetbootin, xixer, rufus, YUMI , Simple-cdd. You should also look at the Debian DebianCustomCD documentation as it will prove more informative than this article could ever be.

I wrote this guide more for educational purposes than anything. It is not necessarily the fastest guide or the best guide for your needs. I hope it is helpful all the same.

Warning : I have highlighted all the places you should be in the [chroot] environment. Be careful! Running some of these commands on your local environment instead of in the chroot can damage your system.

Prerequisites

Install applications we need to build the environment.

Create a directory where we will store all of the files we create throughout this guide.

Bootstrap and Configure Debian

Set up the base Debian environment. I am using stretch for my distribution and i386 for the architecture. Consult the list of debian mirrors.

Please change the URL in this command if there is a mirror that is closer to you.

Chroot to the Debian environment we just bootstrapped.

[chroot] Set a custom hostname for your Debian environment.

[chroot] Figure out which Linux Kernel you want in the live environment.

[chroot] I chose the image linux-image-686 . I also believe live-boot is a necessity. systemd-sys (or an equivalent) is also necessary to provide init.

[chroot] Install programs of your choosing, and then run apt-get clean to save some space. I use —no-install-recommends to avoid superfluous packages. You should decide what you need for your environment.

[chroot] Set the root password. root will be the only user in this live environment by default, but you may add additional users as needed.

[chroot] Exit the chroot.

Create directories that will contain files for our live environment files and scratch files.

Compress the chroot environment into a Squash filesystem.

Copy the kernel and initramfs from inside the chroot to the live directory.

Create a menu configuration file for grub. Please note that the insmod all_video line was needed in my testing to deal with a bug in UEFI booting for one of my machines. Perhaps not everyone will need that line, but I did.

This config instructs Grub to use the search command to infer which device contains our live environment. This seems like the most portable solution considering the various ways we may write our live environment to bootable media.

Create a special file in image named DEBIAN_CUSTOM . This file will be used to help Grub figure out which device contains our live filesystem. This file name must be unique and must match the file name in our grub.cfg config.

Your LIVE_BOOT directory should now roughly look like this.

Create a bootable medium

Please note that there are two separate sets of instructions below for creating a bootable medium for the live environment. One process is titled Create Bootable ISO/CD and the other, separate process, is titled Create Bootable USB.

  • The Create Bootable ISO/CD instructions will result in an .iso image file containing our live environment.
  • The Create Bootable USB instructions will result in our live environment being installed directly to a USB device.

The .iso file we create with the Create Bootable ISO/CD instructions can be burned to a CD-ROM (optical media), or written to a USB device with dd . The functionality that allows this «dd-able» behavior from our .iso file does not come for free. The process is a bit complex, but that resultant behavior is common in many modern live environments such as the Ubuntu installation .iso file.

Please note that writing an .iso file to a USB device is not the same as installing the live environment directly to a USB device. Read more in my Notes which details my discoveries.

Create Bootable ISO/CD

Install the live environment to an .iso file which can be burned to optical media.

As stated above, the .iso file generated by these steps can be written to a USB device with something like dd .

I have separated the instructions for creating a BIOS bootable, UEFI bootable, or combination BIOS + UEFI bootable .iso in order to illustrate the separate processes. Click either «BIOS», «UEFI», or «BIOS + UEFI» and follow the instructions that are appropriate for your needs.

Create a grub BIOS image.

Use cat to combine a bootable Grub cdboot.img bootloader with our boot image.

Generate the ISO file.

Now burn the ISO to a CD and you should be ready to boot from it using a BIOS system.

Create a grub UEFI image.

Create a FAT16 UEFI boot disk image containing the EFI bootloader. Note the use of the mmd and mcopy commands to copy our UEFI boot loader named bootx64.efi .

Generate the ISO file.

Now burn the ISO to a CD and you should be ready to boot from it using a UEFI system.

Create a grub UEFI image.

Create a FAT16 UEFI boot disk image containing the EFI bootloader. Note the use of the mmd and mcopy commands to copy our UEFI boot loader named bootx64.efi .

Create a grub BIOS image.

Use cat to combine a bootable Grub cdboot.img bootloader with our boot image.

Generate the ISO file.

Now burn the ISO to a CD and you should be ready to boot from it using either a UEFI or a BIOS system.

Create Bootable USB

Install the live environment to a USB device.

As stated above, installing a live environment to a USB device is not the same as writing an .iso file to a USB device. The end result is the same for the most part in both those scenarios, but there are subtle differences worth understanding, and there are valid reasons someone may want to install a live environment directly to a USB device rather than writing an .iso file to a USB device.

Читайте также:  Как откатить mac os mohave

I have separated the instructions for creating a BIOS bootable, UEFI bootable, or combination BIOS + UEFI bootable USB device in order to illustrate the separate processes. Click either «BIOS», «UEFI», or «BIOS + UEFI» and follow the instructions that are appropriate for your needs.

I am assuming you have an umounted blank USB drive at /dev/sdz. To allow easily swapping in a real block device, I am using a variable named $disk in these commands.

Export the disk variable.

Create a mount point for the USB drive.

Partition the USB drive using parted . This command creates 1 partition in a traditional MBR layout.

Format the partition.

Mount the partition.

Install Grub for i386-pc booting.

Create a live directory on the USB device.

Copy the Debian live environment files we previously generated to the USB disk.

Copy the grub.cfg boot configuration to the USB device.

Now unmount the disk and you should be ready to boot from it on a BIOS system.

I am assuming you have an umounted blank USB drive at /dev/sdz. To allow easily swapping in a real block device, I am using a variable named $disk in these commands.

Export the disk variable.

Create some mount points for the USB drive.

Partition the USB drive using parted . This command creates 2 partitions in a GPT (Guid Partition Table) layout. One partition for UEFI, and one for our Debian OS and other live data.

Format the UEFI and data partitions.

Mount the partitions.

Install Grub for x86_64 UEFI booting.

Create a live directory on the USB device.

Copy the Debian live environment files we previously generated to the USB disk.

Copy the grub.cfg boot configuration to the USB device.

Now unmount the disk and you should be ready to boot from it on a UEFI system.

I am assuming you have an umounted blank USB drive at /dev/sdz. To allow easily swapping in a real block device, I am using a variable named $disk in these commands.

Export the disk variable.

Create some mount points for the USB drive.

Partition the USB drive using parted . This command creates 3 partitions in a GPT (Guid Partition Table) layout. One partition for the BIOS boot record, one for UEFI, and one for our Debian OS and other live data.

Format the UEFI and data partitions.

Mount the partitions.

Install Grub for x86_64 UEFI booting.

Install Grub for i386-pc booting.

Create a live directory on the USB device.

Copy the Debian live environment files we previously generated to the USB disk.

Copy the grub.cfg boot configuration to the USB device.

Now unmount the disk and you should be ready to boot from it on either a BIOS or UEFI system.

Please note that the result of writing an .iso file generated by the ISO/CD instructions to a USB device is not the same as the other set of instructions for Direct USB.

If you write an .iso to a USB device you are deleting all the data (including partitions/filesystem) on that USB device and replacing them with a read-only iso9660 filesystem, which is normally what we see on CDs! On the other hand, if we use the Direct USB instructions, then the USB device will have traditional partitions that we can read from and write to on any standard machine.

EFI boot equipment may be combined with above ISOLINUX isohybrid for PC-BIOS in a not really UEFI-2.4 compliant way.

I don’t like that not really. compliant bit.

Though, the docs also point out that it does work well. However, I’m trying to consolidate on Grub to avoid a mix of Syslinux configs/files and Grub commands/files.

Figuring out the right syntax and bootloaders to use for each command was a nightmare, and took a lot of time and reading and trial and error. I realize there are simpler commands like grub-mkrescue , but I wanted to explicitly call out the manual commands used for each process.

Supposedly, we can also use -partition_offset so the .iso can be written to USB to help for natural disk layouts on the USB device, but I could not figure out how to get that working.

. facilitates later manipulations of the USB stick by tools for partitioning and formatting.

This blurb is confusing, but I realized it means Grub can be used as the boot equipment for a CD in the same way we would use Syslinux with isohybrid MBR entries.

More compliant with UEFI-2.4 is to decide for either MBR or GPT and to append a copy of the EFI System Partition in order to avoid overlap of ISO partition and EFI partition. Here for MBR:

The resulting ISOs are supposed to boot from optical media and USB stick. One may omit option -eltorito-alt-boot if no option -b is used to make the ISO bootable via PC-BIOS.

That worked wonderfully for me to get a pure Grub result.

This is a super handy command for examining the commands that may have been used to generate an .iso file.

Figuring out which modules are needed for what behavior is frustrating. There are docs, but they do not seem to easily correlate to «this is required to list devices with ls » and similar behavior. I eventually found the magic combo for grub-mkstandalone , which cuts down a few steps. Here’s how to do it with grub-mkimage . More verbose, but easier to debug.

Create a Grub early config file. Note that the label DEBIAN_CUSTOM matters. We must use the same label on our .iso so that Grub always knows where to find our boot media.

Generate a memdisk ourselves.

Bring it all together.

Notes (Rufus Support)

Rufus doesn’t support this guide out of the box. The immediate workaround is to use «DD» mode when using Rufus so that the ISO is copied as-is to a USB device. «ISO» mode in Rufus doesn’t work because the files get extraced from an iso9660 filesystem (the ISO) to a FAT32 or NTFS device (the Rufus-generated USB partitions).

Источник

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