- Install CentOS via PXE and UEFI
- Overview
- Setting up the DHCP and PXE server
- Enable UEFI support in the DHCP server
- Copy UEFI boot files
- Copy CentOS Linux boot images
- Create grub.cfg file
- Configuring Kickstart automated install
- Bootloader command
- Installation screen resolution
- Boot disk device selection
- Capture the %pre logfile
- Disk partitions
- Disable Secure Boot in BIOS
- efibootmgr — manipulate the EFI Boot Manager
- UEFI network boot process
- Загрузочный сервер — как загрузочная флешка, только сервер и по сети
- Начало
- Научим сервер устанавливать различные ОС
- Добавим способность загружать различные дисковые утилиты и тест памяти
- LiveCD
- Антивирусы
- Заключение, оно же и сюрприз
Install CentOS via PXE and UEFI
Overview
This HowTo guide documents how to install CentOS 7 and 8 using PXE on a client host booting by UEFI.
This page assumes that you already have a working DHCP and PXE boot server for installing client hosts using the Legacy_BIOS_boot method. We will show how to support also UEFI booting with PXE. Optionally, you may also use an NFS server to store Kickstart files.
See also our network PXE-booting page for Linux OS installation.
See also some useful pages:
Setting up the DHCP and PXE server
Enable UEFI support in the DHCP server
We assume a Linux DHCP server and add the following to /etc/dhcpd.conf in the top (global) section:
The Client System Architecture Type Option 93 (EFI x86-64) is defined in RFC4578.
Add these options only if you need to support MTFTP (Multicast TFTP) as recommended (but undocumented) in many places:
In the DHCP subnet section(s) define UEFI RFC4578 or PXE (legacy) boot image types in the /tftpboot/uefi/ subdirectory:
- It seems that having the boot file in a subdirectory such as uefi/bootx64.efi will cause the client host PXE to download all further files also from that same uefi/ subdirectory, so you need to place other files there.
- The shimx64.efi bootloader may be required in stead of bootx64.efi in the above /etc/dhcpd.conf.
Copy UEFI boot files
Here we have created a special directory for UEFI boot files on the TFTP server:
We need to copy UEFI boot files from CentOS 7 or 8, and we need these RPMs:
The shim EFI application may be required.
UEFI boot files may be located in different places depending on your distribution, for example in:
Copy the boot files, for example:
Alternatively you can build your own using this RPM:
Then build your own boot file bootx64.efi by:
Copy CentOS Linux boot images
For each CentOS (and other OS) version you should copy Linux boot images to a separate directory on the TFTP server, for example:
and download the PXE boot images:
Other mirror sites may be used in stead of mirror.centos.org.
Create grub.cfg file
The uefi/bootx64.efi boot file will be looking for a Grub configuration file uefi/grub.cfg in the same subdirectory. Create /var/lib/tftpboot/uefi/grub.cfg with the contents:
Other mirror sites may be used in stead of mirror.centos.org.
Additional menu entries may be appended to the above, for example:
It is useful to have a grub.cfg menu item from the TFTP server which allows to boot the system from an existing OS installation on disk. This should be the default menu item. To boot a CentOS system with grubx64.efi (provided by the grub2-efi-x64 package) in the 1st partition of the first disk hd0:
The .efi files of other Linux distributions will be in different subdirectories of /boot/efi/EFI.
If there are multiple disks in the server, Grub will label them as hd0, hd1, hd2, etc. It seems that the numbering of such disks may vary, and if the OS installation is suddenly in disk hd1 in stead of hd0, it is useful to define a fallback boot menu item:
The following method has been suggested, however, it does not seem to work and only returns to a malfunctional BIOS boot menu (tested on a Dell PC):
Configuring Kickstart automated install
Automated installation using Anaconda is possible with UEFI as well as PXE legacy booting. In the above grub.cfg file use:
- inst.ks= Gives the location of a Kickstart file to be used to automate the installation.
For example, the following menu item may be added to grub.cfg to download a Kickstart file ks-centos-7.9.2009-uefi-x86_64.cfg from the NFS server at IP address :
The Kickstart Boot Options are defined in the pages:
Setting up an NFS server is not discussed here.
Bootloader command
The bootloader command (required) specifies how the boot loader should be installed.
You should always use a password to protect your boot loader. An unprotected boot loader can allow a potential attacker to modify the system’s boot options and gain unauthorized access to the system:
If using GRUB2 as the boot loader, sets the boot loader password to the one specified with this option. This should be used to restrict access to the GRUB2 shell, where arbitrary kernel options can be passed. If a password is specified, GRUB2 will also ask for a user name. The user name is always root.
Normally, when you specify a boot loader password using the —password= option, it will be stored in the Kickstart file in plain text. If you want to encrypt the password, use this option and an encrypted password.
To generate an encrypted password, use the:
command, enter the password you want to use, and copy the command’s output (the hash starting with grub.pbkdf2) into the Kickstart file. An example bootloader Kickstart entry with an encrypted password will look similar to the following:
Some systems require a special partition for installing the boot loader. The type and size of this partition depends on whether the disk you are installing the boot loader to uses the Master Boot Record (MBR) or a GUID Partition Table (GPT) schema. For more information, see Boot Loader Installation.
Installation screen resolution
If you have an old server or PC where the VGA graphics adapter only supports screen resolutions up to 1024×768 or 1280×1024, then the kernel in EL8 Linux may select a higher, unsupported screen resolution which gives a flickering monitor with no image! See these pages:
You can add a vga= directive to the kernel line in the GRUB file, something like the following:
You will, of course, see something specific in place of X.Y.Z and you can use numbers other than 792, which gives 1024×768 with 65,536 possible colors. This is a partial list of GRUB VGA Modes:
Linux kernel with 16-bit boot protocol
Switching VESA modes of Linux kernel at boot time can be done by using the “vga=…“ kernel boot parameter. This parameter accept the decimal value of Linux video mode numbers instead of VESA video mode numbers.
The video mode number of the Linux kernel is the VESA mode number plus 0×200:
So the table for the Kernel mode numbers are:
The decimal value of the Linux kernel video mode number can be passed to the kernel in the form “vga=YYY“, where YYY is the decimal value.
The parameter vga=ask is often mentioned, but is not supported by GRUB2.
Last, calculate the decimal value of the Linux video mode number. This simple python command can be used to convert a hex-number 0xYYY:
Boot disk device selection
The server or PC computer may have multiple disk devices, and each device may have different bus interfaces to the system such as NVME or SATA.
When the Kickstart installation starts up, the file given by inst.ks must select, format and partition the system boot disk. However, you do not want to install the Linux OS on a large disk device which should be used for data storage! Another problem is that NVME and SATA devices have different device names in the Linux kernel, for example:
and the correct device name must be given to Kickstart.
A nice and flexible solution to this issue is given in the thread https://access.redhat.com/discussions/3144131. You configure an %include line where you normally partition the disk:
Then you define a pre-install section with %pre, here with a number of improvements:
WARNING: We have some old Intel Xeon Nehalem servers with SATA disks where /sys/block/sda/removable contains an incorrect value of 1!
Capture the %pre logfile
The %pre command can create a logfile:
but since this exists only in the memory file system, the logfile is lost after the system has rebooted.
There are methods to get a copy of the %pre logfile:
Disk partitions
With UEFI systems it is required to configure a special partition:
in your Kickstart file. See also:
It is most convenient to configure boot partitions using reqpart:
- Automatically create partitions required by your hardware platform. These include a /boot/efi for x86_64 and Aarch64 systems with UEFI firmware, biosboot for x86_64 systems with BIOS firmware and GPT, and PRePBoot for IBM Power Systems.
An example Kickstart file section about disk partitions and using reqpart may be:
Disable Secure Boot in BIOS
If the PXE client system BIOS is configured for UEFI Secure_Boot then the PXE boot will fail with an error about an invalid signature.
Workaround: Disable secureboot from BIOS settings.
efibootmgr — manipulate the EFI Boot Manager
efibootmgr is a userspace application used to modify the Intel Extensible Firmware Interface (EFI) Boot Manager. This application can create and destroy boot entries, change the boot order, change the next running boot option, and more.
To show the current boot order:
Some useful command options (see the efibootmgr page):
UEFI network boot process
When a client computer performs an UEFI network boot process, it will first be assigned an IP address and a bootfile name by the DHCP server as described above.
The network adapter will then attempt downloading boot files as well as grub.cfg files by TFTP. However, the download process does not seem to be documented anywhere!
We have observed that the following TFTP file downloads are attempted by the UEFI boot code (rather similar to the BIOS download process):
Then download by TFTP of grub.cfg files are attempted in the following order:
- MAC-address (lower-case hexadecimal numbers) file uefi/grub.cfg-01-ac-1f-6b-f5-a3-0e (for example)
- IP-address (UPPER-CASE hexadecimal numbers) file uefi/grub.cfg-0A028215 (for example)
- IP-address stripping off the trailing digits in item 3 one at a time.
- Finally uefi/grub.cfg
The first match of a grub.cfg file will then be booted.
Hint: Use gethostip from the syslinux package to convert hostnames and IP-addresses to hexadecimal, for example:
IT-wiki: PXE_and_UEFI (последним исправлял пользователь OleHolmNielsen 2021-06-03 09:15:37)
ОчиститьКэш (сохранено 2021-06-03 09:15:37)
Источник
Загрузочный сервер — как загрузочная флешка, только сервер и по сети
Загрузочная флешка с набором нужного софта — замечательный инструмент системного администратора. Казалось бы, что может быть лучше? А лучше может быть загрузочный сервер!
Представьте, вы выбрали в BIOS загрузку по сети и можете установить ОС/вылечить компьютер от вирусов/реанимировать диски/протестировать ОЗУ/etc с PXE Boot сервера, ведь это куда удобнее, нежели бегать с флешкой от машины к машине.
А в случае большого компьютерного парка, такой инструмент и вовсе незаменим.
Вот такое меню встречает нашу команду инженеров при загрузке с PXE
Под катом вас ждет описание всех настроек, а так же небольшой сюрприз.
Начало
Возьмем за основу, что свежеустановленный Debian Wheezy уже весело подмигивает нам консолью.
Подготовим базу для дальнейших манипуляций. Установить и настроить нам потребуется:
- TFTP сервер
- Samba
- Syslinux
- DHCP сервер
- HTTP сервер
- NFS сервер
приведем конфиг /etc/default/tftpd-hpa к виду
и поместим в /etc/tftpd.remap вот такую строку
UPD, дополнение от читателя Aleksey Shipilev
Повыдирал себе волос, пока отдебажил tftp.
Что на ThinkPad X201i, что в VirtualBox загрузка отваливалась с:
PXE-E32: TFTP Open timeout
Судя по всему, PXE агенты умудрились быть не полностью совместимыми, полечилось добавлением «-r blksize»:
TFTP_OPTIONS=»—secure -l -v -r blksize»
В конец файла /etc/samba/smb.conf добавим информацию о папке, где будут лежать инсталляционные файлы Windows.
Cоздаем папку, даем права и рестартим самбу
3. Syslinux
Скачиваем и заливаем в корень TFTP сервера все необходимое
Перейдем к настройке
Создадим конфиг основного меню и внесем начальные настройки
дефолтный конфиг переместим, создадим вместо него свой и перезапустим DHCP демон
5. HTTP
Пока просто установим, а зачем он нам понадобился будет понятно далее по тексту.
6. NFS
Ровно так же как и предыдущий пункт.
Если все сделано правильно, то при загрузке какой-либо машины с этого DHCP/PXE/TFTP сервера мы увидим следующее:
Научим сервер устанавливать различные ОС
Для установки нам будут доступны:
- Windows 2008R2/20012R2
- Debian 6/7
- Centos 6/7
- Ubuntu 12.04/12.10/14.04/14.10
- FreeBSD 9.2/10.1
- VMware ESXi 5.0/5.5
Структура меню, а следовательно и файл /srv/tftp/pxelinux.cfg/default притерпели изменения.
Листинг директории /srv/tftp/pxelinux.cfg/
Пути к папкам, где лежат установочные файлы для каждой из ОС, описаны относительно корня TFTP сервера, т.е. /srv/tftp .
Например для FreeBSD указано
следовательно в корне TFTP нужно создать папки freebsd/10/ , при этом обратите внимание на права
У всех должно быть право на чтение — это правило справедливо для всех файлов отдаваемых по TFTP.
И еще пара слов о установке FreeBSD.
Логин / пароль для входа в загружаемый iso: root / mfsroot(либо root без пароля).
Плюс пара примеров скриптов инсталяции FreeBSD на ZFS:
1. RAID6 из 4-х дисков.
2. RAID1 из 2-х дисков.
О том как подготовить Windows к установке с PXE мы писали ранее.
Различие с данной инсталляцией составляет лишь то, что здесь мы можем установить и Windows 2008R2 и Windows 2012R2(впрочем и Windows 7/8 тоже, нужно только подготовить файлы дистрибутива и winpe соответствующим образом). После загрузки winpe мы монтируем папку /srv/tftp/images/ , где содержаться файлы для установки ОС от Microsoft:
и запускаем нужный инсталятор.
Для автоматизации, через startnet.cmd, я набросал вот такое меню:
Теперь осталось разобраться с VMware.
Как вы заметили, конфиг для установки гипервизоров несколько отличается от остальных — именно тут нам и понадобится HTTP сервер.
В /var/www создадим папки vmw5.5, vmw5.0, а в папках сделаем симлинки на конфиг
О том как подготовить, например, Debian к установке с PXE написано здесь, но я на этом останавливаться не стану.
Добавим способность загружать различные дисковые утилиты и тест памяти
А я расскажу зачем мы ставили еще и NFS сервер.
Как видно из конфига загрузки SystemRescueCD, необходимые этому LiveCD файлы он подтягивает монтируя каталог по протоколу NFS. Сервер уже установлен, остается только отредактировать /etc/exports и перезапустить серверный демон.
Предполагаю у вас возник резонный вопрос — «Что тут делает LiveCD, если для них есть отдельный пункт?»
SystemRescueCD содержит массу полезных программ для работы с диском(например таких как GParted и testdisk) и поэтому он доступен и здесь и в LiveCD.
LiveCD
в конец default добавилось
Для загрузки Trinity Rescue Kit CD и Plop Live в /etc/exports нужно добавить строки:
и отправить команду рестарта NFS демону.
Несколько слов о выбраных LiveCD.
Debian 7 LiveCD
Этот CD — сборка одного из наших инженеров, включающая в себя следующее:
Логин / пароль: root / ServerClub
HirensBootCD
Едва ли нуждается в представлении, содержит множество полезных утилит.
Подробнее можно ознакомиться здесь.
Грузится достаточно долго, не работает MiniXP и Linux. Остальные утилиты доступны для использования.
Trinity Rescue Kit CD
Со слов разработчиков, создан для восстановления ОС Windows.
Содержит утилиты для сброса паролей, антивирусы, программу для клонирования «компьютера» по сети(при чем на несколько компьютеров одновременно), а так же многое другое.
Подробнее здесь.
SystemRescueCD
Основан на Gentoo, предназначен для восстановления Linux систем.
Включает в себя большое количество всевозможных программ для администрирования, со списком можно ознакомится по ссылке.
Plop Live
LiveCD с тремя полноценными DE на выбор, а так же необходимым админским софтом.
Антивирусы
- Kaspersky Rescue Disk 10
В отдельном представлении оба антивируса не нуждаются.
О Kaspersky Rescue disk подробнее можно прочесть здесь.
С описанием AVG Recsue CD вас ознакомит данный url.
Заключение, оно же и сюрприз
На протяжении статьи я сознательно не давал объяснений где взять и как подготовить контент, потому как действия эти весьма тривиальны и только перегрузили бы текст.
В качестве сюрприза предлагаю вам два варианта нашей сборки, доступные по ссылкам ниже:
- Архив со всем контентом /srv/tftp (ссылка на торрент файл, прямая ссылка)
- Архив всей ОС (ссылка на торрент файл, прямая ссылка)
В первом случае необходимо самостоятельно подготовить сервер(в этом поможет глава «Начало» данного эпоса), разархивировать содержимое архива и внести корректировки сообразно реалиям вашей среды.
Второй случай подразумевает установку на голое железо или виртуальную машину.
Вкратце шаги по развертыванию сборки из полного архива ОС будут такими:
1. Загрузиться с Linux LiveCD.
2. Разметить диск и отформатировать разделы.
3. Примонтировать «/» раздел.
4. Распаковать архив.
5. Установить загрузчик.
6. Перезагрузиться.
7. Настроить ОС в соответствии вашей сети и начать пользоваться.
Логин / пароль: root / ServerClub.
ВАЖНО: Если в вашей сети есть работающий dhcp сервер, то перед запуском нашей сборки отключите в ней автостарт dhcp.
Источник