- Archiso (Русский)
- Contents
- Установка
- Настройка live носителя
- Установка пакетов
- Собственный локальный репозиторий
- Предотвращение установки пакетов, принадлежащих основной группе
- Установка пакетов из multilib
- Добавление файлов в образ
- Загрузчик
- UEFI Secure Boot
- Вход в систему
- Изменение автоматического входа в систему
- Сборка ISO
- Удаление рабочей директории
- Использование ISO
- Archiso
- Contents
- Installation
- Prepare a custom profile
- Profile structure
- Selecting packages
- Custom local repository
- Packages from multilib
- Adding files to image
- Kernel
- Boot loader
- UEFI Secure Boot
- systemd units
- Login manager
- Changing automatic login
- Users and passwords
- Build the ISO
- Removal of work directory
- Using the ISO
- Test the ISO in QEMU
- Tips and tricks
- Prepare an ISO for an installation via SSH
- Automatically connect to a Wi-Fi network using iwd
- Adjusting the size of root partition on the fly
- Troubleshooting
- Window manager freezes
Archiso (Русский)
Archiso — набор bash скриптов, предназначенных для создания полностью функциональных Live-CD/DVD и Live-USB на базе Arch Linux. Это тот же инструмент, который используется для создания официальных образов, но он довольно гибкий инструмент, который может быть использован как для создания дисков восстановления или установочных, так и для специализированных live-CD/DVD/USB систем. Сердце Archiso — mkarchiso. Для получения подробного описания всех его опций достаточно вызвать его без параметров, так что здесь будет описанно только создание live диска своими руками.
Если вам требуется только краткое изложение требований и процесса сборки, вы можете также воспользоваться официальной документацией проекта.
Contents
Установка
Archiso поставляется с двумя «профилями»: releng и baseline.
- Если вы хотите создать полностью индивидуальную версию Arch Linux, предварительно установленной со всеми вашими любимыми программами и конфигурациями, используйте профиль releng.
- Если вы просто хотите создать основу для live CD, без предварительно установленных пакетов и минимальной конфигурацией, используйте baseline.
Теперь скопируйте профиль на Ваш выбор, в каталог (
/archlive используется в примере ниже), в котором вы можете вносить корректировки. Выполните следующую команду, заменив profile либо на releng , либо на baseline .
- Если вы используете профиль releng для создания полностью индивидуального образа, вы можете переходить к секции #Настройка live носителя.
- Если вы используете профиль baseline для создания пустого образа, то вам не нужно его настраивать, поэтому переходите к секции #Сборка ISO.
Настройка live носителя
В этом разделе подробно описывается настройка создаваемого вами образа, определение пакетов и конфигураций, которые вы хотите, чтобы ваш live образ содержал.
Внутри каталога archlive , созданного в #Установка, имеется ряд файлов и каталогов; мы рассмотрим лишь несколько из них, в основном:
- packages.x86_64 — это где вы перечисляете построчно пакеты, которые вы хотите установить, и
- каталог airootfs — это каталог, действующий как наложение, и именно там вы делаете все настройки.
Как правило, любые административные задачи, которые вы обычно делаете после новой установки, могут быть выполнены в скрипте archlive/airootfs/root/customize_airootfs.sh , за исключением установки пакетов. Скрипт должен быть написан с точки зрения новой среды, поэтому / в скрипте означает корень ISO-образа, который создается.
Установка пакетов
Отредактируйте списки пакетов в packages.x86_64 чтобы указать, какие пакеты должны быть установлены на live носителе.
Собственный локальный репозиторий
This article or section is a candidate for merging with Pacman/Tips and tricks (Русский)#Собственный локальный репозиторий.
Для подготовки своих пакетов или пакетов из AUR/ABS, вы можете создать собственный локальный репозиторий. Если вам нужна поддержка нескольких архитектур, примените соответствующие меры для предотвращения ошибок в будущем. Каждая архитектура должна иметь собственное дерево каталогов:
Затем вы можете добавить свой репозиторий, поместив следующее в
/archlive/pacman.conf выше других записей (для более высокого приоритета):
Если пакет подходит, repo-add выполняет проверку. Иначе, вы столкнетесь с сообщениями об ошибках, подобными этому:
Предотвращение установки пакетов, принадлежащих основной группе
По умолчанию /usr/bin/mkarchiso , скрипт, который используется
/archlive/build.sh , вызывает один из скриптов arch-install-scripts с именем pacstrap без флага -i , что заставляет Pacman не ждать ввода пользователя во время процесса установки.
При внесении в черный список основных пакетов группы путем добавления их в строку IgnorePkg в файле
/archlive/pacman.conf , Pacman спрашивает, должны ли они все еще быть установлены, а это значит, что они будут при обходе ввода пользователя. Чтобы избавиться от этих пакетов существует несколько вариантов:
- «Грязный» способ: Добавьте флаг -i в каждую строку, вызывающую pacstrap в /usr/bin/mkarchiso .
- «Чистый»: Создайте копию /usr/bin/mkarchiso , в которую вы добавите флаг и адаптируете
/archlive/build.sh , так чтобы он вызывал измененную версию скрипта mkarchiso.
- Расширенный способ: Создайте функцию для
/archlive/build.sh , которая явно удаляет пакеты после основной установки. Это принесет вам удовольствие от того, что вам не придется много вводить во время процесса установки.
Установка пакетов из multilib
Чтобы установить пакеты из репозитория multilib, вам нужно просто раскомментировать его в
Добавление файлов в образ
Каталог airootfs действует как наложение, считайте его корневым каталогом ‘/’ в вашей текущей системе, поэтому любые файлы, которые вы размещаете в этом каталоге, будут скопированы при загрузке.
Поэтому, если у вас есть набор скриптов iptables в вашей текущей системе, которые вы хотите использовать на вашем live образe, скопируйте их:
Размещение файлов в домашнем каталоге пользователей немного отличается. Не помещайте их в airootfs/home , а вместо этого создайте каталог skel внутри airootfs/ и разместите их там. Затем мы добавим соответствующие команды в customize_airootfs.sh , которые мы собираемся использовать для их копирования при загрузке и выяснения разрешений.
Сначала создайте каталог skel:
Теперь скопируйте файлы ‘home’ в каталог skel, например для .bashrc :
/archlive/airootfs/root/customize_airootfs.sh , и создается новый пользователь, файлы из каталога skel будут автоматически скопированы в новую домашнюю папку, а разрешения будут установлены правильно.
Аналогичным образом, требуется обратить внимание на особые файлы конфигурации, которые находятся где-то внизу по иерархии. В качестве примера конфигурационный файл /etc/X11/xinit/xinitrc находится на пути, который может быть перезаписан путем установки пакета. Чтобы поместить файл конфигурации, следует поместить пользовательский xinitrc в
/archlive/airootfs/etc/skel/ , а затем изменить customize_airootfs.sh , чтобы переместить его соответствующим образом.
Загрузчик
Файл по умолчанию должен работать прекрасно, поэтому вам не нужно трогать его.
Из-за модульной природы isolinux вы можете использовать множество дополнений, так как все *.c32 файлы копируются и доступны вам. Посмотрите официальный сайт syslinux и репозиторий git archiso. Используя указанные аддоны, можно сделать визуально привлекательные и сложные меню. Для получения дополнительной информации смотрите здесь.
UEFI Secure Boot
Если вы хотите загружать Archiso в окружении с включённым UEFI Secure Boot, вы должны использовать подписанный загрузчик. Вы можете воспользоваться инструкциями из статьи Secure Boot#Booting an installation medium.
Вход в систему
Запуск X при загрузке выполняется путем включения службы systemd менеджера входа в систему. Если вы знаете, какой файл .service нуждается в символической ссылке: Отлично. Если нет, то вы можете легко узнать в случае, если вы используете одну и ту же программу в системе, в которой вы собираете свой iso. Просто используйте:
Теперь создайте ту же самую символическую ссылку в
/archlive/airootfs/etc/systemd/system . Для LXDM:
Это позволяeт запустить LXDM при загрузке системы из вашего live образа.
В качестве альтернативы вы можете просто включить службу в airootfs/root/customize_airootfs.sh вместе с другими включенными там службами.
Если вы хотите, чтобы графическая среда фактически запускалась автоматически во время загрузки, обязательно отредактируйте airootfs/root/customize_airootfs.sh и замените
Изменение автоматического входа в систему
Файлы настроек автоматического входа для getty расположены в airootfs/etc/systemd/system/getty@tty1.service.d/autologin.conf .
Вы можете отредактировать этот файл для изменения автоматического входа пользователя в систему:
Или удалите его вообще для отключения автоматического входа в систему.
Сборка ISO
Создайте ISO, который затем можно записать на компакт-диск или USB, запустив:
- -w указывает рабочий каталог. Если параметр не указан, по умолчанию он будет работать в текущем каталоге.
- -o указывает каталог, в который будет помещен созданный ISO-образ. Если параметр не указан, по умолчанию он будет выводить в текущий каталог.
- Следует отметить, что файл профиля profiledef.sh не может быть указан при запуске mkarchiso, только путь к файлу
Замените /путь/до/профиля/ на путь к вашему пользовательскому профилю или на /usr/share/archiso/configs/relng/ , если вы создаете неизмененный профиль.
При запуске сценарий загрузит и установит указанные вами пакеты в рабочую_директорию/x86_64/airootfs , создаст образы ядра и инициализации, применит ваши настройки и, наконец, создаст ISO в выходной каталог.
Удаление рабочей директории
Временные файлы копируются в рабочую директорию. После успешного создания ISO рабочую директорию и его содержимое можно удалить. Например.:
Использование ISO
Для получения дополнительной информации смотрите статью Руководство по установке.
Источник
Archiso
Archiso is a highly-customizable tool for building Arch Linux live CD/USB ISO images. The official images are built with Archiso. It can be used as the basis for rescue systems, linux installers or other systems. This wiki article explains how to install Archiso, and how to configure it to control aspects of the resulting ISO image such as included packages and files. Technical requirements and build steps can be found in the official project documentation. Archiso is implemented with a number of bash scripts. The core component of Archiso is the mkarchiso command. Its options are documented in mkarchiso -h and not covered here.
Contents
Installation
Prepare a custom profile
Archiso comes with two profiles, releng and baseline.
- releng is used to create the official monthly installation ISO. It can be used as a starting point for creating a customized ISO image.
- baseline is a minimalistic configuration, that includes only the bare minimum packages required to boot the live environment from the medium.
To build an unmodified version of the profiles, skip to #Build the ISO. Otherwise, if you wish to adapt or customize one of archiso’s shipped profiles, copy it from /usr/share/archiso/configs/profile-name/ to a writable directory with a name of your choice. For example:
Proceed to the following sections to customize and build the custom profile.
Profile structure
An archiso profile contains configuration that defines the resulting ISO image. The profile structure is documented in /usr/share/doc/archiso/README.profile.rst [1].
Selecting packages
Edit packages.x86_64 to select which packages are to be installed on the live system image, listing packages line by line.
Custom local repository
To add packages not located in standard Arch repositories (e.g. custom packages or packages from AUR/ABS), set up a custom local repository and add your custom packages to it. Then add your repository to pacman.conf as follows:
Packages from multilib
To install packages from the multilib repository, simply uncomment that repository in pacman.conf .
Adding files to image
The airootfs directory is used as the starting point for the root directory ( / ) of the live system on the image. All its contents will be copied over to the working directory before packages are installed.
Place any custom files and/or directories in the desired location under airootfs/ . For example, if you have a set of iptables scripts on your current system you want to be used on you live image, copy them over as such:
Similarly, some care is required for special configuration files that reside somewhere down the hierarchy. Missing parts of the directory structure can be simply created with mkdir(1) .
By default, permissions will be 644 for files and 755 for directories. All of them will be owned by the root user. To set different permissions or ownership for specific files and/or folders, use the file_permissions associative array in profiledef.sh . See README.profile.rst for details.
Kernel
Although both archiso’s included profiles only have linux , ISOs can be made to include other or even multiple kernels.
First, edit packages.x86_64 to include kernel package names that you want. When mkarchiso runs, it will include all work_dir/airootfs/boot/vmlinuz-* and work_dir/boot/initramfs-*.img files in the ISO (and additionally in the FAT image used for UEFI booting).
mkinitcpio presets by default will build fallback initramfs images. For an ISO, the main initramfs image would not typically include the autodetect hook, thus making an additional fallback image unnecessary. To prevent the creation of an fallback initramfs image, so that it does not take up space or slow down the build process, place a custom preset in archlive/airootfs/etc/mkinitcpio.d/pkgbase.preset . For example, for linux-lts :
Finally create boot loader configuration to allow booting the kernel(s).
Boot loader
Archiso supports syslinux for BIOS booting and systemd-boot for UEFI booting. Refer to the articles of the boot loaders for information on their configuration syntax.
mkarchiso expects that systemd-boot configuration is in the efiboot directory, and syslinux configuration in syslinux and isolinux directories.
UEFI Secure Boot
If you want to make your Archiso bootable on a UEFI Secure Boot enabled environment, you must use a signed boot loader. You can follow the instructions on Secure Boot#Booting an installation medium.
systemd units
To enable systemd services/sockets/timers for the live environment, you need to manually create the symbolic links just as systemctl enable does it.
For example, to enable gpm.service , which contains WantedBy=multi-user.target , run:
The required symlinks can be found out by reading the systemd unit, or if you have the service installed, by enabling it and observing the systemctl output.
Login manager
Starting X at boot is done by enabling your login manager’s systemd service. If you do not know which .service enable, you can easily find out in case you are using the same program on the system you build your ISO on. Just use:
Now create the same symlink in archlive/airootfs/etc/systemd/system/ . For LXDM:
This will enable LXDM at system start on your live system.
Changing automatic login
The configuration for getty’s automatic login is located under airootfs/etc/systemd/system/getty@tty1.service.d/autologin.conf .
You can modify this file to change the auto login user:
Or remove it altogether to disable auto login.
Users and passwords
To create a user which will be available in the live environment, you must manually edit archlive/airootfs/etc/passwd , archlive/airootfs/etc/shadow , archlive/airootfs/etc/group and archlive/airootfs/etc/gshadow .
For example, to add a user archie . Add them to archlive/airootfs/etc/passwd following the passwd(5) syntax:
Generate a password hash with openssl passwd -6 and add it to archlive/airootfs/etc/shadow following the syntax of shadow(5) . For example:
Add the user’s group and the groups which they will part of to archlive/airootfs/etc/group according to group(5) . For example:
Create the appropriate archlive/airootfs/etc/gshadow according to gshadow(5) :
Make sure /etc/shadow and /etc/gshadow have the correct permissions:
After package installation, mkarchiso will create all specified home directories for users listed in archlive/airootfs/etc/passwd and copy work_directory/x86_64/airootfs/etc/skel/* to them. The copied files will have proper user and group ownership.
Build the ISO
Build an ISO which you can then burn to CD or USB by running:
- -w specifies the working directory. If the option is not specified, it will default to work in the current directory.
- -o specifies the directory where the built ISO image will be placed. If the option is not specified, it will default to out in the current directory.
- It should be noted the profile file profiledef.sh cannot be specified when running mkarchiso, only the path to the file
Replace /path/to/profile/ with the path to your custom profile, or with /usr/share/archiso/configs/releng/ if you are building an unmodified profile.
When run, the script will download and install the packages you specified to work_directory/x86_64/airootfs , create the kernel and init images, apply your customizations and finally build the ISO into the output directory.
Removal of work directory
The temporary files are copied into work directory. After successfully building the ISO , the work directory and its contents can be deleted. E.g.:
Using the ISO
Test the ISO in QEMU
Install the optional dependencies qemu and edk2-ovmf .
Use the convenience script run_archiso to run a built image using QEMU.
The virtual machine can also be run using UEFI emulation:
Tips and tricks
Prepare an ISO for an installation via SSH
To install Arch Linux via SSH without any interaction with the system, an SSH public key must be placed in authorized_keys .
Adding the SSH key can either be done manually (explained here), or by cloud-init.
To add the key manually, first copy Archiso’s releng profile to a writable directory. The following example uses archlive .
Create a .ssh directory in the home directory of the user which will be used to log in. The following example will be using the root user.
Add the SSH public key(s), which will be used to log in, to authorized_keys :
Set correct permissions and ownership for the .ssh directory and the authorized_keys file:
Finally build the ISO. Upon booting the ISO, OpenSSH will start and it will be possible to log in using the corresponding SSH private key(s).
Automatically connect to a Wi-Fi network using iwd
Create /var/lib/iwd/ inside the profile’s airootfs directory and set the correct permissions:
Follow the instructions in iwd#Network configuration and iwd.network(5) to create a network configuration file for your Wi-Fi network.
Save the configuration file inside archlive/airootfs/var/lib/iwd/ .
Adjusting the size of root partition on the fly
The factual accuracy of this article or section is disputed.
If you get the following error message when downloading files or installing packages in the booted ISO environment, you may need to shutdown and adjust the size of the root partition while booting the Archiso again.
To adjust the size of the root partition on the live Archlinux system, hit the TAB key to edit the kernel parameters. Append cow_spacesize=2G at the end to get 2G size for the root partition. Press Enter to continue booting into the live system. You can check the size of the filesystems by running:
You can also adjust the root partition size on the fly by running this command:
See more boot parameters here
Troubleshooting
Window manager freezes
If you want to use a window manager in the Live CD then you must add the necessary and correct video drivers, or the WM may freeze on loading.
Источник