Create linux live usb image

Создание Live USB-дисков в Linux с помощью команды dd

Существует несколько программ с графическим интерфейсом, предназначенных для создания Live USB-дисков. Вероятно, в Linux самой популярной из них является Etcher. В Ubuntu есть собственный инструмент для решения этой задачи — Startup Disk Creator.

Но продвинутые пользователи Linux, ради удобного и быстрого создания Live USB-дисков, постоянно обращаются к команде dd .

Это — CLI-инструмент, который даёт тому, кто его выбирает, мощные возможности по копированию и конвертированию файлов.

Обычно dd используют для того, чтобы записывать ISO-файлы на внешние носители информации, вроде USB-дисков. Потом такой носитель информации можно использовать, например, для установки записанного на него Linux-дистрибутива на обычный компьютер или на ноутбук.

Тут я расскажу о создании загрузочных USB-дисков с помощью dd . В частности, разберу команды, которые нужны для того, чтобы сначала найти в системе нужный диск, а потом записать на него ISO-файл.

Создание Live USB-дисков на основе ISO-файлов с помощью команды dd

Прежде чем я покажу вам пошаговый план работы с dd — хочу в двух словах рассказать об этой команде и продемонстрировать пример её использования.

Вот как выглядит вызов команды dd для записи ISO-файла на USB-диск:

Разберём эту команду.

Разбор команды dd

Сначала в командной строке вводят dd . Это, как и должно быть, просто имя команды, которую мы собираемся запустить.

Далее указывают следующее: if=»./filename.iso» . Имя опции if расшифровывается как input file — входной файл. Тут мы сообщаем dd о том, какой именно ISO-файл хотим записать на USB-диск.

После этого вводят путь к USB-диску. В данном случае это выглядит как of=»/dev/sdb» . Здесь of означает output file, то есть — выходной файл.

При работе с dd стоит помнить о том, что то, что указывают в опции of , необязательно должно представлять собой файл в системе, используемой для работы. Тут можно указывать нечто вроде пути к внешнему устройству (именно так и сделано в нашем примере). И хотя выглядит этот путь как путь к обычному файлу, он, на самом деле, символизирует устройство, подключённое к компьютеру.

Опция status может принимать одно из трёх значений: none , noxfer и progress .

Если она установлена в значение progress — это приведёт к тому, что dd будет периодически сообщать нам о том, сколько данных из ISO-файла уже перенесено на диск, и о том, сколько времени, приблизительно, осталось до завершения операции.

Если использовать тут значение none , то dd ничего не будет сообщать о ходе процедуры, но, если в процессе записи образа на диск возникнут ошибки, программа об этом сообщит.

Вариант noxfer позволяет скрыть некоторые сведения, выводимые после того, как перенос данных на USB-диск завершён. Например — сведения о том, сколько времени заняла процедура копирования ISO-файла.

И, наконец, мы воспользовались вариантом fsync опции conv . Это приводит к тому, что dd не сообщит об успешном завершении операции до тех пор, пока весь ISO-файл не будет записан на USB-диск.

Если эту опцию не указывать, dd , всё равно, правильно запишет данные (и при этом может показаться, что команда работает быстрее, чем с этой опцией), но может оказаться так, что системе понадобится некоторое время на то, чтобы, при попытке безопасно извлечь USB-диск, сообщить о том, что это возможно. Дело в том, что без этой опции завершение записи образа проводится в фоновом режиме, что позволяет пользователю в это время заняться какими-то другими делами.

Читайте также:  Soundflower mac os ��� ����������

Теперь, когда мы разобрали команду dd , рассмотрим весь процесс записи ISO-файлов на USB-диски.

Но, прежде чем мы продолжим, хочу вас кое о чём предупредить. Командная строка — это палка о двух концах. Будьте очень осторожны, выполняя команды наподобие dd . А именно — тщательно проконтролируйте то, что в этой команде используется правильный выходной файл. Ошибка при указании опции of может привести к форматированию главного системного диска и к уничтожению файлов операционной системы, установленной на компьютере.

Шаг 0. Загрузка ISO-файла

Само собой разумеется то, что для того, чтобы записать на USB-диск ISO-файл, этот файл сначала надо где-то раздобыть.

Я, испытывая команду dd , буду записывать на диск образ Ubuntu 20.04, который можно скачать отсюда.

Шаг 1. Выяснение метки USB-диска

Сначала подключим USB-диск к компьютеру.

В вышеприведённом примере я, настраивая опцию of , ввёл /dev/sdb . Обычно USB-диски, подключённые к системе, доступны именно по этому пути, но это — не некое железное правило, которое справедливо абсолютно всегда.

В вашей системе это может быть какой-то другой путь. Выяснить это можно с помощью команды lsblk . Выполнив эту команду нужно поискать диск, размер которого соответствует USB-диску, на который планируется записать образ.

Поиск USB-диска с помощью средств командной строки

Если вы предпочитаете для решения подобных задач использовать программы с графическим интерфейсом — можете найти путь к нужному диску с помощью чего-то наподобие GNOME Disks.

Поиск USB-диска с помощью инструмента с графическим интерфейсом

Теперь, когда нам известен путь к нужному носителю информации, можно создать Live USB-диск.

Шаг 2. Запись ISO-файла на USB-диск

Откроем терминал в директории, в которой находится загруженный ISO-файл, и запустим следующую команду (запуская эту команду у себя — замените, если нужно, /dev/sdb на путь к вашему USB-диску):

После выполнения этой команды нужно будет некоторое время подождать и dd создаст Live USB-диск.

Создание Live USB-диска

Итоги

После завершения работы dd в вашем распоряжении окажется USB-диск, с которого можно загрузиться. Но, пожалуй, важнее то, что теперь вы лучше узнали инструменты командной строки Linux, освоили кое-что новое, позволяющее ускорить и упростить решение некоторых задач.

Чем вы пользуетесь для создания Live USB-дисков в Linux?

Источник

Creating and using a live installation image

Downloading Fedora

You can download Fedora from https://getfedora.org/.

There are multiple desktops available for use with Fedora. Each has a slightly different look and feel and offers varying levels of customization. You can use the Fedora Workstation image, which comes with the GNOME desktop by default, and then change your environment afterwards by installing additional packages, or you can download a spin image which will give you a different environment out of the box. Visit Fedora Spins for more information.

You can also take advantage of Fedora Labs. Fedora Labs is a selection of curated bundles of purpose-driven software and content as curated and maintained by members of the Fedora Community. These may be installed as standalone full versions of Fedora or as add-ons to existing Fedora installations. Visit Fedora Labs for details.

Please refer to Fedora Installation Guide for getting help on the process of installing Fedora.

Creating and using live USB

You can write all Fedora ISO images to a USB stick, making this a convenient way on any USB-bootable computer to either install Fedora or try a live Fedora environment without writing to the computer’s hard disk. You will need a USB stick at least as large as the image you wish to write.

Using Fedora Media Writer

The official and supported tool to create a Fedora USB stick is the Fedora Media Writer utility, which was formerly known as LiveUSB Creator. To learn more about this application and how to use it, refer to the Preparing for Installation chapter of the Fedora Installation Guide.

Читайте также:  Linux вывести только колонку

Fedora Media Writer destroys all data on the USB stick. If you need a non-destructive write method (to preserve existing data on your USB stick) or support for ‘data persistence’, you can use the livecd-iso-to-disk utility on Fedora.

Using GNOME Disk Utility

This method will destroy all data on the USB stick. If you need a non-destructive write method (to preserve existing data on your USB stick) and/or support for ‘data persistence’, you can use the livecd-iso-to-disk utility on Fedora.

This method is considered unsupported. You can use it on your own risk.

This method is for people running Linux, or another unix with GNOME, Nautilus and the GNOME Disk Utility installed. Particularly, if you are using a distribution other than Fedora which does not support Flatpak, this may be the easiest available method. A standard installation of Fedora, or a standard GNOME installation of many other distributions, should be able to use this method. On Fedora, ensure the packages nautilus and gnome-disk-utility are installed. Similar graphical direct-write tools may be available for other desktops, or you may use the command-line direct write method.

Download a Fedora image, choose a USB stick that does not contain any data you need, and connect it.

Run Nautilus (Files), open the Overview by pressing the Start/Super key, type Files, and hit Enter .

Find the downloaded image, right-click on it, go to Open With, and click Disk Image Writer.

Select your USB stick as the Destination, and click Start Restoring.

Command line methods

These methods are considered unsupported. You can use them on your own risk.

Using the livecd-iso-to-disk tool

This method will destroy all data on the USB stick if the —format parameter is passed.

The livecd-iso-to-disk method is slightly less reliable than Fedora Media Writer and can be used reliably only from within Fedora: it does not work in Windows or macOS, and is not supported (and will usually fail) in non-Fedora distributions. However, it supports three advanced features which FMW does not include:

You may use a non-destructive method to create the stick, meaning existing files on the stick will not be destroyed. This is less reliable than the destructive write methods, and should be used only if you have no stick you can afford to wipe.

On live images, you can include a feature called a persistent overlay, which allows changes made to persist across reboots. You can perform updates just like a regular installation to your hard disk, except that kernel updates require manual intervention and overlay space may be insufficient. Without a persistent overlay, the stick will return to a fresh state each time it is booted.

On live images, you can also have a separate area to store user account information and data such as documents and downloaded files, with optional encryption for security and peace of mind.

By combining these features, you can carry your computer with you in your pocket, booting it on nearly any system you find yourself using.

It is not a good idea to try and write a new Fedora release using the version of livecd-iso-to-disk in a much older Fedora release: it is best to only use a release a maximum of two versions older than the release you are trying to write.

Ensure the livecd-tools package is installed: dnf install livecd-tools .

Читайте также:  Полное отключение защитника windows 10 через реестр

Remember to identify your USB stick’s device name first. In all cases, you can add the parameter —efi to render the stick bootable in native UEFI mode. Detailed usage information is available by running: livecd-iso-to-disk —help or man livecd-iso-to-disk .

To make an existing USB stick bootable as a Fedora image, without deleting any of the data on it, make sure that the USB drive is not mounted before executing the following, and give the root password when prompted:

In case it is not possible to boot from a disk created with the method shown above, before re-partitioning and re-formatting, often resetting the master boot record will enable booting:

Using the —format option in the following command will erase all data on the USB drive.

If necessary, you can have livecd-iso-to-disk re-partition and re-format the target stick:

To include a persistent filesystem for /home , use the —home-size-mb parameter. For example:

This will create a 2 GiB filesystem that will be mounted as /home each time the stick is booted, allowing you to preserve data in /home across boots.

To enable ‘data persistence’ support — so changes you make to the entire live environment will persist across boots — add the —overlay-size-mb parameter to add a persistent data storage area to the target stick. For example:

Here, 2048 is the desired size (in megabytes) of the overlay. The livecd-iso-to-disk tool will not accept an overlay size value greater than 4095 for VFAT, but for ext[234] filesystems it is only limited by the available space.

Due to the way it’s currently implemented, every single change to this form of overlay, writes AND deletes, subtracts from its free space so it will eventually be «used up» and your USB stick will no longer boot. You can use dmsetup status live-rw to see how much space remains in the overlay.

The output will contain something like snapshot 42296/204800 , indicating that 4229 of 204800 512-byte sectors are allocated. Because of these limitations, it is advisable to use the system-level persistence sparingly, for configuration changes and important security updates only. Or, if you have sufficient disk space available, changes to the LiveOS root filesystem snapshot can be merged into a new copy of the root filesystem.

You can combine —home-size-mb and —overlay-size-mb , in which case data written to /home will not exhaust the persistent overlay.

Using a direct write method

This method will destroy all data on the USB stick. If you need a non-destructive write method, to preserve existing data on your USB stick, and/or support for data persistence , you can use the livecd-iso-to-disk utility on Fedora.

This method directly writes the image to the USB stick much like Fedora Media Writer or GNOME Disk Utility, but uses a command line utility named dd . Like the other direct write methods, it will destroy all data on the stick and does not support any of the advanced features like data persistence, but it is a very reliable method. The dd tool is available on most Unix-like operating systems, including Linux distributions and macOS, and a Windows port is available. This may be your best method if you cannot use Fedora Media Writer or GNOME Disk Utility, or just if you prefer command line utilities and want a simple, quick way to write a stick.

Identify the name of the USB drive partition. If using this method on Windows, with the port linked above, the dd —list command should provide you with the correct name.

Источник

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