Gentoo livecd как пользоваться
Перейти к содержимому

Gentoo livecd как пользоваться

  • автор:

Создание LiveCD дистрибутива на базе Gentoo Linux

В руководстве рассказывается о том как создать свой LiveCD диск на основе Gentoo Linux. Диск будет полностью русифицирован, произведена установка KDE и обеспечено автоматическое монтирование flash накопителей. В качестве загрузчика рассматривается ISOLINUX. Раньше был GRUB, но пришлось от него отказаться, так как он не работает на некоторых ноутбуках. Созданный по этой инструкции диск можно будет постоянно совершенствовать, устанавливать новые пакеты, вообщем можно делать все то что можно делать с обычным дистрибутивом установленным на вашем ПК.

Подготовительные действия

Для сборки необходимо создать определенную структуру каталогов, где создавать
— в принципе без разницы. Я создавал в домашней директории. Структура
следующая:

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

Собирать livecd будем из второй стадии. Скачиваем ее из сети и копируем в distr и распаковываем в каталог сборки. Распаковывать следует с root правами, иначе будут проблемы с созданием устройств в каталоге /dev.

# tar -C source/ -pxjvf distrib/stage2-i686-2007.0.tar.bz2

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

Для того чтобы легко отличать консоль в chroot окружении от консоли основной системы, рекомендую для первой изменить приглашение коммандной строки и вместо просто "#"написать например "(LIVECD) #". Для этого копируем заготовленный в conf директории файл root/bashrc в каталог source/root/ (добавив в начало названия точку).

Для сборки образа, на ПК предварительно должны быть установлены пакеты squashfs-tools и cdrtools. Первый для работы с файловой системой SquashFS, второй для записи CD дисков.

# emerge -av squashfs-tools cdrtools

Собираем базовую систему

Сейчас можно входить (chroot’иться как еще говорят) в собираемую систему и начинать подгонять ее под свои потребности.

Если все прошло нормально — на экране не должно быть никаких ругательных сообщений, а приглашение командной строки выглядеть вот так: "(LIVECD) #". Сейчас мы находимся в только-что распакованной из stage2 системе.

Общий план работ таков:

Установить имя машины/домена, профиль, дописать USE флагов в make.conf,создать /etc/fstab.

Установить часовой пояс, перевести часы в режим Local, сгенерировать русские локали, установить русскую расскладку клавиатуры и экранный шрифт.

Выполнить emerge -e system и emerge -e world для получения Stage3.

Не забыть установить пароль root’у.

Собрать ядро, настроить загрузчик и попробовать перезагрузиться.

Установить свои приложения.

Создать ISO образ и записать его на диск.

Первые два пункта за вас может выполнить подготовленный скрипт "_prepare.sh". Написан он был потому как собрать livecd получилось не с первого раза, и делать одно и тоже на только-что распакованных stage-2 порядком надоело. Его нужно скопировать куда нибудь в source директорию и выполнить один раз для свеже распакованного stage-2. Скопировать можно например в /root или пря мо в корень (важно не забыть перед созданием ISO образа его оттуда удалить).

Напомню что все действия происходят в chroot окружении.

Подготавливаем и русифицируем систему.

(LIVECD) # rm _prepare.sh

Устанавливаем основные утилиты для управления пакетами

(LIVECD) # emerge -av gentoolkit

(LIVECD) # emerge -e system

Обновляем конфигурационные файлы обновленных приложений

Здесь нужно быть внимательным и не затереть те конфигурационные файлы которые

мы сами изменяли (или их изменил скрипт _prepare.sh). Это касается русского шрифта, раскладки клавиатуры и прочее. Вообщем прежде чем в ответ на вопрос dispatch-conf’a жать ‘u’, внимательно посмотрите какой файл он хочет обновить. Если это файлы: clock, consolefont, hostname или keymaps — жмите ‘z’ (не обновлять).

Проверяем целостность зависимостей системы

Тоже самое про мир, пересобираем, обновляем конфигурационные файлы и проверяем целостность зависимостей.

(LIVECD) # emerge -e world

Пересборка system на Turion64X2 заняла приблизительно 2.5 часа, world — 3 ч.

При emerge -e system могут быть проблемы с perl. Если такое случиться

-делать так (ставиться будет примерно минут 15):

(LIVECD) # emerge —oneshot gdbm db

(LIVECD) # emerge -N —oneshot —nodeps perl

После можно снова пробовать emerge -e system.

Возможно где-то в середине сборка system прервется с ошибкой на пакете sys-apps/attr. Ошибка будет выглядеть так: "libexpat.so.0: cannot open shared objects file: No such file or directory". Если это случилось — создаем сиволическую ссылку с libexpat.so на libexpat.so.0, и затем пробуем продолжить сборку, т.е. делаем

(LIVECD) # ln -s /usr/lib/libexpat.so /usr/lib/libexpat.so.0

(LIVECD) # emerge —resume

Обнаружил небольшой недочет при сборке с использованием portage от 05.03.2008. emerge -e system прерывается на пакете ‘which-2.19’ с ошибкой "error: readline/rlstdc.h: No such file or directory". На момент сборки этого пакета уже должна стоять библиотека readline, но ее нет. Устанавливаем ее сами и продолжаем сборку system. Если подробно, то:

(LIVECD) # emerge -av readline

(LIVECD) # emerge —resume

Если будут еще какие-либо проблемы — скачайте или обновитесь до самого свежего архива портежей. Не поможет — идите на bugzilla.gentoo.org.

4.Устанавливаем пароль root’у

Создаем пользователя livecd

(LIVECD) # useradd -m -G users,wheel,audio,video,cdrom,cdrw,usb -s /bin/bash livecd

(LIVECD) # passwd livecd

Устанавливаем splash темы для красивой графической загрузки

(LIVECD) # emerge -av splash-themes-livecd

Устанавливаем и компилируем ядро

(LIVECD) # emerge -av gentoo-sources

genkernel должен быть не старее чем 3.4.10_pre4. На момент написания этого руководства такой версии в стабильной ветке небыло. Если у вас тоже-самое -разрешаем устанавливать его из тестовой (

x86), для этого выполним

(LIVECD) # echo ‘sys-kernel/genkernel

(LIVECD) # emerge -av genkernel

(LIVECD) # genkernel all —gensplash=livecd-2007.0

Устанавливаем и добавляем в автозагрузку Gentoo LiveCD скрипты

Снимаем маскировку (установлена разработчиками для того чтобы предупредить о том, что скрипты предназначены только для использования вместе с livecd)

(LIVECD) # echo ‘app-misc/livecd-tools’ >> /etc/portage/package.unmask

(LIVECD) # echo ‘x11-misc/mkxf86config’ >> /etc/portage/package.unmask

(LIVECD) # echo ‘sys-apps/hwsetup’ >> /etc/portage/package.unmask

livecd-tools нужен версии не ниже 1.0.40_pre1. На момент написания этого руководства такой версии в стабильной ветке небыло. Если у вас тоже-самое — разрешаем устанавливать его из тестовой (

x86), для этого выполним

(LIVECD) # echo ‘app-misc/livecd-tools

(LIVECD) # emerge -av livecd-tools

libkudzu нужен не ниже чем 1.2.57.1, если будет устанавливаться более старая версия — отвечаем ‘no’ и разрешаем libkudzu из тестовой ветки.

(LIVECD) # echo ‘sys-libs/libkudzu

(LIVECD) # rc-update add autoconfig default

(LIVECD) # emerge -av syslinux

(LIVECD) # mkdir /boot/isolinux

(LIVECD) # cp /usr/lib/syslinux/isolinux.bin /boot/isolinux

(LIVECD) # cp /boot/kernel-genkernel-x86-2.6.23-gentoo-r6/boot/isolinux/vmlinuz

(LIVECD) # cp /boot/initramfs-genkernel-x86-2.6.23-gentoo-r6 /boot/isolinux/initrd

Из директории с конфиг. файлами копируем в /boot/isolinux файл isolinux.cfg.

Создаем образ и пробуем его загрузить. Выходим из chroot окружения и запускаем скрипт "build.sh"

Процесс сборки образа длиться примерно минут 5. После него забираем iso файл в директории livecd. Можно записать его на болванку, но лучше для этих целей поставить например VirtualBox или VMWare, потому как удобнее и быстрее.

Записать на CD можно так:

# cdrecord -v -eject speed=10 fs=8m dev=/dev/cdrw image.iso

или если это DVD то так:

# growisofs -dvd-compat -Z /dev/dvd=image.iso

Образ должен загрузиться, когда дойдет до приглашения — введите root и ваш пароль. Если все так — пол дела сделано. LiveCD грузиться. Сейчас желательно создать архив с каталогом livecd на случай если при дальнейших манипуляциях что нибудь пойдет не так — можно будет откатиться.

Установка KDE

(LIVECD) # emerge -av xorg-server

Устанавливаем оригинальный драйвера nVidia

(LIVECD) # emerge -av nvidia-drivers

Правим таблицу соответсвия устройство — драйвер для nVidia карт. Открываем файл /usr/share/hwdata/Cards.

3.1. Находим строку NAME NVIDIA Legacy и меняем название драйвера ‘vesa’ на ‘nv’.

3.2. Находим строку NAME NVIDIA GeForce и меняем название драйвера с ‘vesa’ на ‘nvidia’.

Устанавливаем минимальный набор KDE(LIVECD) # emerge -av kdm kdebase-startkde kde-i18n

Добавляем в автозапуск xdm и указываем в нем запускемый оконный менеджер В файле /etc/conf.d/xdm переменной DISPLAYMANAGER присваиваем значение "kdm"

(LIVECD) # rc-update add xdm default

Настройка автомонтирования съемных устройств

(LIVECD) # emerge -auv dbus hal pmount

(LIVECD) # rc-update add dbus default

(LIVECD) # rc-update add hald default

(LIVECD) # gpasswd -a livecd plugdev

Включаем русскую раскладку и переключатель en/ru

7.1. Открываем файл /usr/sbin/mkxf86config.sh и удаляем строку вида

Option "XkbOptions" "grp:alt_shift_toggle,grp_led:scroll"

Что еще можно сделать

* Автологин в текстовой консоли не под root’ом

(LIVECD) # emerge -av mingetty

Прописываем его в /etc/inittab вместо agetty.

c1:12345:respawn:/sbin/agetty 38400 tty1 linux

Как нужно исправить:

c1:12345:respawn:/sbin/mingetty —autologin root —noclear tty1

Естественно что вместо root можно вписать любого пользователя.

Правим файл /sbin/rc

Находим вот такую секцию (приблизительно это строка N 500)

then ebegin "Updating inittab" livecd_fix_inittab eend $? /sbin/telinit q &>/dev/null fi

и делаем ее такой

then ebegin "Updating inittab" /bin/true #livecd_fix_inittab eend $? /bin/true #/sbin/telinit q &>/dev/null

Свое сообщение после init’a

Открываем файл /sbin/rc, ищем строку вида ‘echo -e " Copyright’ и добавляем
ниже нее свое сообщение.

Автологин в KDE

Открываем файл /usr/kde/3.5/share/config/kdm/kdmrc и прописываем пользователя
в строки ‘DefaultUser’ и ‘AutoLoginUser’.

Красивый, настроенный и подогнанный под себя рабочий стол

Запускаем созданный LiveCD, загружаемся в KDE и настраиваем его под себя. Все, шрифты, поведение окон, курсор занятости, панели и пр. Затем сжимаем свой домашний каталог (/home/livecd) и копируем его на флешку. Выходим из LiveCD, chroot’имся в source и распаковываем в каталог /home/livecd/ сохраненные на флешке настройки.

Intro¶

The first thing you want to know is that its a very hands on Linux distribution, its not easy.

Gentoo takes a long time to install because you’re building everything from source and it’s being built for YOUR computer.

This guide is set up for a very basic Linux system, nothing else like kde or gnome, thats up to you.

It’s setup not to give you to much information, but enough to make the right choices needed to get the system up and running.

The Official Gentoo Linux install guide is more Links here x86 or amd64

But its way to much information for most people.

Basic guide lines:

READ EVERYTHING, don’t skip around. don’t skim the text, but do read the whole thing once to get an idea whats going on.

Use your brain! Stop and think about what its saying.

If you have a problem, try to solve it yourself by using the forum or wiki.

You’re going to need some sort of Linux Live CD.

This can be the Gentoo Live CD or any other, it doesn’t really matter as long as it’s running current Linux Kernel.

You can get the minimal Gentoo Live-CD more Links here x86 or amd64.

NOTE: If you’re going to do a 64bit install, you’re going to need a livecd that is 64bit.

The Basics¶

Next you need to know what type of hardware is in your computer.

The most basic thing you need to know is if your hard drive is SATA or the old 80pin style.

If its SATA remember this > sda

If not > hda

Second thing is, do you have winblows already installed on this hard drive? If so YOU need to partition it with a windows program like partition magic.

There is a free partition Live-CD called GParted, you can download it from here
If you do this your going to need around 10GB of disk space for /(root) and a swamp hard drive space. And you do not need to format it or anything just leave it “raw” or unused.
You can have /boot on the same partition as the / (root) or make 3 different partitions.

The Partitions¶

Boot to the Live CD, If you cant get this far, go back to windows.
For any other Live CD you want to get to a term, and from that term you need to get to root, it should have a # sign.
For a lot of Live CD’s to get root: sudo su —

If you have more then one hard drive, the “a” part on sda or hda will changed based on which drive you’re going to use.
a = the 0 hard drive, 0 in the Linux would pretty much means the first.
For this step hda1 is going to mean the first partition, on the first hard drive.

So if your going to install Gentoo on the 2nd hard drive it would be hdb or sdb.

If you already have windows installed, your going to need to shift one number higher on the partitions.
Windows will be on hda1 or sda1, so you need to start with the number 2 for the partitions.
This next part will be permanent so choose wisely.

Formatting¶

Remember if you already have a partition, you need to +1 on the partition numbers.
Also note if your using a SATA drive its not going to be hda, its going to be sda.

Basic Package Setup¶

The date format is a bit weird but here is the format:
date MMDDhhmmYYYY syntax (Month, Day, hour, minute and Year)

Try to get the time as close as possible.

This would be a very good time to see if your internet connection is working.

Try: ifconfig

Look for eth0 or eth1, they should have an IP address, if not, run: net-setup

Try: ping www.google.com

If that doesn’t work, you may have to try another Live CD or something else isn’t right on your network.

If you’re thinking of going 64bit, and its you’re first time installing Gentoo, go i686 aka x86.

Most proprietary software will not work right, or work at all in 64bit.

If your going to do a 64bit install use this next line

[More Links here] (http://www.gentoo.org/main/en/mirrors.xml)

Gentoo Env Setup¶

This part will setup how you want to run your system.

If setup the right way the first time, you shouldn’t have any issues.

make.conf this will make or break your system.

Missing 1 character will mess up your system or it wont even build.

If your CPU supports SSE3 add -msse3 to your CFLAGS line

Even more information here

CHOST=”i686-pc-linux-gnu” If you want a 32bit Install

CHOST=”x86_64-pc-linux-gnu” If you want a 64bit Install

Once your CHOST is set NEVER CHANGE IT!

This is also the part wher you make the choice on if you want a 64bit install of Gentoo or not.

You can have a 64bit cpu running only x86/i686(32bit) code, there are a few pluses for this reason, like Flash and codec video/audio support.

ACCEPT_KEYWORDS=”x86” if your chost is i686-pc-linux-gnu

ACCEPT_KEYWORDS=”amd64” if your chost is x86_64-pc-linux-gnu

MAKEOPTS=”-j2” This is core/cpu + 1, so a single cpu/core 2, dual core 3.

INPUT_DEVICES=”keyboard mouse evdev”

All possible options:
keyboard mouse acecad aiptek calcomp citron digitaledge dmc dynapro elo2300 elographics evdev fpit hyperpen jamstudio joystick magellan magictouch microtouch mutouch palmax penmount spaceorb summa synaptics tek4957 ur98 vmmouse void wacom

VIDEO_CARDS=”nvidia” fglrx for ATI video cards

All possible options:
nvidia apm ark chips cirrus cyrix dummy fbdev fglrx glint i128 i740 i810 imstt mach64 mga neomagic nsc nv r128 radeon rendition s3 s3virge savage siliconmotion sis sisusb tdfx tga trident tseng v4l vesa vga via vmware voodoo

There are already some global USE flags already set.

1 rule: In Gentoo always check your USE flags before installing anything. -pv OR -av

2 rule: If you dont know what the USE flag does/is for don’t enable it.

Theres so much information about USE flags here
Make sure you READ IT ALL!
THIS is the master list of all use flags, which is very usefull

BASE COMPILE¶

This part will take 2-3 hours, its about 83 packages.

If your getting blocked packages like e2fsprogs, ss, and com_err.
Do this:

You can thank the Gentoo devs for not putting out a 2008.2

Kernel Compile¶

For now you can use this guide to build your kernel.

If you use genkernel, your grub setup will be different.

I will make a kernel section soon on this site, its a very tricky thing to do, but it will be done.

The basic way of doing it is:

Some people have asked me to make a kernel guide, well that is a lot of work every single release of the kernel.

Every kernel version the layout changes, sometimes a little, sometimes a lot.

The main thing you want to keep in mind is the commands: dmesg and lspci they will help you a lot in your config.

Grub and fstab¶

If you have windows on hda1, its going to be hd0,0 for root

Also if you did your install on hdb its going to be hd1,0

Also if your using SATA use sda not hda

Services and Final setup¶

How to setup your network if you want to setup a static IP and or other configurations read this page.

You can really screw up your install with /etc updates.

This is just a few things you DO NOT UPDATE with dispatch-conf or etc-update.

Anything YOU edited in /etc/conf.d

Use your brain when updating or editing anything in /etc

A Few Last Things…¶

If your going to install kde use ‘emerge -av kdebase-meta’

Same with gnome use ‘emerge -av gnome-light’

This will save you A LOT of time. It will install just the basics.

Always check and set your use flags before you install or update anything.

I don’t know how much I can stress this fact. You will have to repeat -pv after you change your use flags because they may have added more packages to the listing, which they have use flags.

LiveUSB

This article explains how to create a Gentoo LiveUSB or, in other words, how to emulate a x86 or amd64 Gentoo LiveCD using a USB drive. This is particularly useful for installing Gentoo on a modern laptop with no CD-ROM drive.

Although the instructions found in this document aim at emulating a Gentoo LiveCD using a USB drive, they should work for any arbitrary block device as long as the device names are adjusted accordingly.

Many other methods available on different operating systems should work for creating bootable LiveUSB drives for Gentoo installation.

Содержание

Prerequisites

In order to boot a LiveUSB, the following will be needed:

  • Bootable USB drive with enough space to write the image to. When using the Gentoo Minimal Installation CD, at least 1GB. (Generally, the bigger the better.)
  • A computer with support for

Access to the following is needed for creating a LiveUSB:

  • A computer running Gentoo (or alternatively another Linux distribution)
  • A computer running Microsoft Windows with the appropriate software (see the Windows section below)
  • A computer able to run the dd command (e.g. MacOS)

Choosing an installation media for Gentoo

The architecture appropriate Gentoo Minimal Installation CD iso can be downloaded and used to install from a command line interface, as a «light» installation option. There is currently (2022) a Gentoo LiveGUI USB Image which can provide a more ergonomic option (e.g. open the handbook in another window and copy paste commands with a middle mouse click to a terminal emulator, use a GUI IRC client for support, etc.).

When downloading, adjust the architecture ( x86 , amd64 , arm , sparc , etc.) portion of the URL to match the system’s CPU. Gentoo mirrors are here.

The Gentoo bootable images are by no means the only thing that can be used to install Gentoo — almost any modern LiveCD should work. Use whatever feels the most comfortable.

Convert the ISO image to hybrid mode

Most modern LiveCD’s, like Gentoo are already in hybrid mode. If the LiveUSB does not boot, then it may be that the image will have to be converted to hybrid mode. Hybrid mode means image will enable the ISO to boot from both a CD-ROM device or a USB drive.

Convert the ISO with the following command:

The isohybrid command comes as part of the sys-boot/syslinux package.

Using dd to write the ISO image to a USB drive

When using the Gentoo Installation CD ISOs, it is sufficient to directly copy the ISO contents onto the USB device. The dd command can be used to accomplish this. For instance, assuming the USB device is at /dev/sdc :

The dd utility will not return any progress output (it can provide some progress output, but not without some finagling). The command will exit without any errors when it completes the transfer successfully (i.e. with no output at all). Depending on the size of the ISO image and the speed of the USB device, this process could some time. Be patient!

Once complete, the USB drive should be bootable.

On Windows, the dd command is also available through various projects, such as Cygwin, GNUWin32, or Chrysocome.

The remainder of this document explains how to setup a vfat partition that is writable using the syslinux bootloader instead of isolinux.

Creating bootable LiveUSB drives from Linux systems

Automatic drive-wide installation script

This script will assist in writing a LiveUSB stick suitable for both BIOS and UEFI systems.

Manually preparing a LiveUSB drive

Preparing the USB drive
Partitioning the drive

Create a FAT16 partition on the USB drive and mark it bootable using fdisk . An example partitioning scheme can be seen below:

Creating the filesystem

Create a FAT16 filesystem on the USB drive using mkfs.fat :

Installing a Master Boot Record (MBR)

Install the precompiled Master Boot Record (MBR) from syslinux on the USB drive:

Copying the files
Mounting the Gentoo Minimal Installation CD

Download a Gentoo Minimal Installation CD for the system’s architecture from a the main site’s download page and mount the ISO image on /mnt/cdrom as shown below:

Adjust the /path/to/isofile.iso as necessary to the location of the downloaded Minimal Installation CD ISO.

Mounting the LiveUSB

Mount the newly formatted USB drive on /mnt/usb as shown below:

Copying the files

Copy the files from the Minimal Installation CD to the LiveUSB. The files need to be reordered since syslinux will be used as the bootloader instead of isolinux :

Unmount the ISO image:

Adjusting the bootloader configuration

Adjust the syslinux configuration file using sed as shown below. The slowusb parameter will introduce some extra delays before attempting to mount the filesystem. This is needed to allow the USB drive to settle upon detection.

Installing a bootloader
Unmounting the drive

Make sure the USB drive has been unmounted before installing the bootloader:

Installing syslinux

Finally install the syslinux bootloader on the USB drive:

Creating bootable LiveUSB drives under Windows

Rufus

Rufus is a free and open source project created to write images to USB drives, with a variety of operating systems. It tends to be faster than the Universal USB installer (see in the next section).

Rufus can be downloaded from the project’s homepage.

Rufus is easy to use and should be mostly self explanatory. For more information, see Rufus’ FAQ page.

Universal USB Installer

Universal USB installer is one of the oldest Linux-capable LiveUSB creators for Windows systems. It supports most Linux distributions, and has a simple, helpful wizard for selecting the Linux distribution. For Gentoo Minimal Installation CDs, however, select the Try Unlisted Linux ISO which is at the very bottom of the list. Select the proper USB drive to format and extract Linux to, and click Create .

Universal USB installer can be downloaded from its homepage.

Booting

Insert the USB drive and turn on the computer, make sure the BIOS (or EFI firmware) has been set to boot from USB. If all goes well,a standard syslinux prompt should appear on the screen.

When attempting to boot from a USB device, be sure to select or enable USB drives as bootable devices in the system’s firmware interface. If the ISO is UEFI capable, it may be necessary to enable booting UEFI devices as well. This is typically performed via toggle options in the BIOS or UEFI firmware interface.

The boot order may need to be adjusted in the system’s firmware for USB devices to boot first, although it is usually easier to hit the appropriate key (commonly either F2 or Delete ) and manually select the USB device as a one-time boot option from the list of bootable devices.

If installing Gentoo, follow the generic installation instructions found in the Gentoo Handbook appropriate to the system’s architecture from here on!

Name already in use

gentoo_guide / gentoo_guide.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Установка Gentoo Linux + Arch + LiveCD + Haskell

Так уж сложилось, что я программирую на Haskell. И к сожалению нет ни одного LiveCD с готовой средой разработки на Haskell. Поэтому я сделал свой собственный LiveCD. В качестве операционных систем я использую Gentoo Linux и Arch Linux. Помимо создания LiveCD, я подробно опишу процесс установки обеих операционных систем и затем мы приступим к их настройке и созданию LiveCD.

Это руководство написано для тех, кто хочет подробно разобраться в установке Gentoo Linux и Arch Linux. Написано очень много замечательный программ, так что все и не охватить и существует огромное количество способов, сделать то или иное действие. В этом руководстве я постараюсь освятить подробно установку Gentoo + Arch, так как ее вижу я. И первый вопрос, почему Gentoo + Arch. Можно ведь было описать отдельно процесс установки Gentoo и отдельно процесс установки Arch. Это руководство именно о том, как использовать обе операционные системы одновременно. Приведу скриншот, того о чем идет речь.

Gentoo Screenshots

Конечный результат должен быть таким

  • установленный и настроенный Gentoo Linux (x86_64)
  • установленный и настроенный Arch Linux (x86_64)
  • возможность загрузить любую из операционок как xen dom0
  • возможность загрузить вторую из операционок как xen domU
  • возможность загрузить любую из операционок под lxc
  • возможность одновремменно использовать программы из gentoo и arch
  • установленная и настроенная среда разработки на haskell
  • созданный LiveCD

Замечательно, теперь когда определелились с целями, давайте опишем как все это у нас будет работать.

  • UEFI -> GRUB -> Xen -> Dom0 (Gentoo) -> LXC (Arch)

Почему в этой схеме Dom0 -> LXC. На самом деле работать будут все варианты. Я же привел тот, который использую чаще всего. Вот другие

  • UEFI -> GRUB -> Xen -> Dom0 (Arch) -> LXC (Gentoo)
  • UEFI -> GRUB -> Xen -> Dom0 (Gentoo) -> DomU (Arch)
  • UEFI -> GRUB -> Xen -> Dom0 (Arch) -> DomU (Gentoo)

Наша установка будет соответствовать всем этим вариантам одновременно. Устанавливать будем не спеша, по ходу дела настраивая системы. Опишем чуть больше подробностей.

  • grub версии 2, соберем его с поддержкой Crypto Luks и ZFS
  • grub дешифрует корневую файловую систему, на которой расположено все (gentoo — /boot + / + /home и arch — /boot + / + /home)
  • файловая система ZFS. Почему ZFS? Посмотрите список плюшек
  • грузится xen
  • будем по возможности использовать hardened профили и версии программ
  • Если грузится gentoo dom0, то xen грузится тот который установлен в gentoo
  • Если грузится arch dom0, то xen грузится тот который установлен в arch

После загрузки dom0, вы попадаете в соответствующую операционку и запускаете если хотите по желанию

  • либо xen domu со второй операционкой
  • либо lxc со второй операционкой

То есть у нас есть ровно 2 операционки, каждая из которых может быть загружена 3 способами, либо на физической машине, либо под xen, либо под lxc. Главное можно работать как в gentoo, так и в arch одноврмененно.

Теперь опишу как я буду настраивать среду разработки на haskell

  • горячие клавиши мы повесим на все используя actkbd + xbindkeys (собранный с guile)
  • менеджер окон — мы будем использовать dwm (+ пачти) + dmenu (+ скрипты)
  • терминал urxvt + скрипты на perl
  • tmux + tmuxinator + плагины
  • zsh (+zgen + плагины)
  • vim + плагины
  • ghc
  • stack
  • hoogle
  • idris
  • .

Лучший способ стаить gentoo из под gentoo

Итак, чтобы установить gentoo нам необходима gentoo!

Подготовка диска и установка нужных пакетов

  • добавим в файл /etc/portage/package.accept_keywords следующие строки

app-misc/pax-utils — ELF utils that can check files for security relevant properties sys-kernel/genkernel — Gentoo automatic kernel building scripts sys-kernel/spl — The Solaris Porting Layer is a Linux kernel module which provides many of the Solaris kernel APIs sys-fs/zfs-kmod — Linux ZFS kernel module for sys-fs/zfs sys-fs/zfs — Userland utilities for ZFS Linux kernel module

Если portage ругается на блокироку zfs и genkernel, значит надо поставить genkernel новее, так как он понимает zfs с определенной версии. Именно поэтому мы добавили

amd64 для genkernel в package.accept_keywords.

Готовим раздел для установки

Загрузим необходимые модули ядра, если они еще не загружены. Делаем

Смотрим с помощью lsmod и dmesg | tail -50, что все удачно.

Давайте посмотрим текущее разбиение диска

Gentoo Screenshots

Мы удалим разделы /dev/sda5, /dev/sda6, /dev/sda7, и в получившемся свободном пространстве создадим раздел. Но предварительно, мы в файле /etc/conf.d/dmcrypt закомментируем строки, создающие swap раздел, так как нумерация gpt разделов изменится и мы не хотим потерять данные.

Gentoo Screenshots

Теперь создадим раздел

Gentoo Screenshots

Для зачистки можно использовать wipe и shred. Мы используем shred. Чтоб ничего не потерять настоятельно рекомендую прочитать man shred. Чтобы узнать сколько это заняло времени, напишем перед кодмандой time.

  • -v — показывать прогресс операции
  • -f — изменить права доступа если необходимо
  • -z — в конце заполнить нулями, чтобы спрятать shredding
  • -n — проделать N раз вместо 3 по умолчанию

Gentoo Screenshots

Чтобы выбрать какие алгоритмы использовать, попробуйте сделать

Я выбрал следующие

Посмотрим, что все хорошо

Теперь добавим в один из слотов дополнительные ключи дешифровки. Вначале сгенерим ключ и положим его в файл /etc/keys/luks_key_sda5.key

Теперь добавим его к нашему разделу

Посмотрим, что все хорошо

Увидим, что Key Slot 0: ENABLED и Key Slot 1: ENABLED. Теперь установим права и аттрибуты

Проверим, что все хорошо ls -l и lsattr. Подключаем раздел

Ура, у нас теперь есть /dev/mapper/sda5crypt. Чтобы в дальнейшем ничего не перепутать (помимо sda5 у нас есть еще другие sdaN), создадим symlink, который и будем дальше использовать.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *