- How to create a Linux RPM package
- More about automation
- What is an RPM package?
- How to create an RPM package
- Installing the required software
- Place the script in the designated directory
- Create a .spec file
- Checking the .spec file on error (rpmlint)
- Building the package (rpmbuild)
- Installing the RPM package
- Verify the package has been installed
- See what’s in the RPM package
- Removing the RPM package
- RootUsers
- Guides, tutorials, reviews and news for System Administrators.
- How To Install An RPM File In Linux
- Install RPM File With Yum
- Install RPM File With DNF
- Install RPM File With RPM Command
- How To Download RPM Files
- Summary
- ИТ База знаний
- Полезно
- Навигация
- Серверные решения
- Телефония
- Корпоративные сети
- RPM — установка и использование в Linux
- Установка
- Удаление
- Полезно?
- Почему?
How to create a Linux RPM package
Photo by Ketut Subiyanto from Pexels
This article shows you how to package a script into an RPM file for easy installation, updating, and removal from your Linux systems. Before I jump into the details, I’ll explain what an RPM package is, and how you can install, query, remove, and, most importantly, create one yourself.
This article covers:
- What an RPM package is.
- How to create an RPM package.
- How to install, query, and remove an RPM package.
More about automation
What is an RPM package?
RPM stands for Red Hat Package Manager. It was developed by Red Hat and is primarily used on Red Hat-based Linux operating systems (Fedora, CentOS, RHEL, etc.).
An RPM package uses the .rpm extension and is a bundle (a collection) of different files. It can contain the following:
- Binary files, also known as executables ( nmap , stat , xattr , ssh , sshd , and so on).
- Configuration files ( sshd.conf , updatedb.conf , logrotate.conf , etc.).
- Documentation files ( README , TODO , AUTHOR , etc.).
The name of an RPM package follows this format:
Some packages also include a shorthand version of the distribution they were built for, such as:
How to create an RPM package
You’ll need the following components to build an RPM package:
- A workstation or a virtual machine running an RPM-based distribution, such RHEL or Fedora.
- Software to build the package.
- Source code to package.
- SPEC file to build the RPM.
Installing the required software
The following packages need to be installed to build the RPM package:
After installing rpmdevtools , create the file tree you need to build RPM packages:
You build RPM packages as a normal (not root) user, so your build environment is placed into your home directory. It contains this directory structure:
- The BUILD directory is used during the build process of the RPM package. This is where the temporary files are stored, moved around, etc.
- The RPMS directory holds RPM packages built for different architectures and noarch if specified in .spec file or during the build.
- The SOURCES directory, as the name implies, holds sources. This can be a simple script, a complex C project that needs to be compiled, a pre-compiled program, etc. Usually, the sources are compressed as .tar.gz or .tgz files.
- The SPEC directory contains the .spec files. The .spec file defines how a package is built. More on that later.
- The SRPMS directory holds the .src.rpm packages. A Source RPM package doesn’t belong to an architecture or distribution. The actual .rpm package build is based on the .src.rpm package.
A .src.rpm package is very flexible, because it can be built and re-built on every other RPM-based distribution and architecture.
You’re now familiar with what each directory holds, so now create a simple script to distribute:
This creates a shell script called hello.sh , which prints «Hello world» to the terminal. It’s simple, but it’s enough to demonstrate packaging.
Place the script in the designated directory
To build a package for your script, you must put your script in the directory that the RPM build system expects it to be in. Create a directory for it, using semantic versioning as most projects do, and then move hello.sh into it:
Most source code is distributed as an archive, so use the tar command to create an archive file:
Then move the tarball you’ve just created into the SOURCES directory:
Create a .spec file
An RPM package is defined by a .spec file. The syntax of a .spec file is strict, but rpmdev can generate a boilerplate file for you:
This generates a file called hello.spec , which you must move to the SPECS directory. Run tree
/rpmbuild to see what the directory structure looks like:
The generated hello.spec file provides a good starting point, but it doesn’t have any specific information about what you’re building. The generated .spec file assumes that I am going to compile and build software.
You’re packaging a Bash script, so there’s some simplification you can do. For instance, there’s no Build process because there’s no code to compile. I’ve added BuildArch: noarch because this package is valid for 32-bit, 64-bit, Arm, and any other CPU architecture that runs Bash.
I’ve also added Requires: bash so that the package ensures that Bash is installed. This simple «hello world» script runs on any shell, of course, but that’s not true for all scripts, so this is a good way to demonstrate dependencies.
As you can tell, there are a lot of shortcuts in .spec files. They’re called macros, and there’s an excellent list of what’s available in the Fedora packaging documentation. It’s important to use macros in your .spec files. They help ensure consistency across all RPM systems, they help you avoid mistakes in filenames and version numbering, and they make it easier to update the .spec file when you release a new version of your script.
For example, it’s required that you specify exactly which files are installed under the %files section. Here I’ve explicitly put the following line:
This works because I want the script to go to % (which is a macro that translates to /usr/bin by default, but is configurable when users want to install to a different location, such as /usr/local/bin ). You can verify macro values by running:
Other useful macros:
- %
name of the package (as defined in the Name: field) - %
version of the package (as defined in the Version: field) - % <_datadir>shared data ( /usr/sbin by default)
- % <_sysconfdir>configuration directory ( /etc by default)
Checking the .spec file on error (rpmlint)
The rpmlint command can find errors in .spec files:
There are 2 errors reported, but they’re both acceptable. There’s no code to build, so there’s no need for a %build section, and the source archive is a local file and has no network URL.
Everything looks good.
Building the package (rpmbuild)
To build the RPM package, use the rpmbuild command. Earlier in this tutorial, I mentioned the difference between the .src.rpm (Source RPM package) and the .rpm package.
To create the .src rpm package:
The flags -bs have the following meanings:
To create the binary .rpm package:
The flags -bb have the following meanings:
Use -ba to build both.
After the build process is finished, you have the following directory structure:
Installing the RPM package
After a successful build of the package, you can install the RPM package using the dnf command:
It can alternately be installed with the rpm command directly:
Verify the package has been installed
To verify the package has correctly been installed, run the following command:
The %changelog entry of a package can be viewed, too:
See what’s in the RPM package
It’s easy to see which files an RPM package contains:
Removing the RPM package
Removing the package from the system is just as easy as installing it. You can use the dnf command:
Источник
RootUsers
Guides, tutorials, reviews and news for System Administrators.
How To Install An RPM File In Linux
RPM files exist to make the software installation and upgrading process easier. They allow us to simply use an RPM file to install a software package, and when combined with package managers such as Yum or DNF we will also get all required dependencies downloaded and installed easily.
Not all distributions of Linux support RPM. Generally RPM files are used in RHEL based distributions such as CentOS and Fedora to name a couple, however it has also been ported elsewhere. If you find that your distribution does not support installing an RPM file, you may need to look at other options such as .deb files in Ubuntu/Debian.
If you’ve downloaded an RPM file from the Internet, there are a couple of tools you can use to install it. Personally I prefer to use Yum/DNF, these act like a front-end to the RPM command and will maintain an up to date database of package dependencies.
Install RPM File With Yum
Normally when installing a package from a repository with the yum command, you would run ‘yum install httpd’ and it will simply download the required RPM file from a configured repository. We can instead use ‘yum install file.rpm’ and specify a local RPM file that we have to install.
We can also use ‘yum localinstall file.rpm’, however the man page notes that this is maintained for legacy reasons only and suggests using install instead.
Not only is the httpd RPM file that we specified installed, but so are the listed additional dependencies that the httpd package needs to work properly.
Note that unlike the RPM command covered later, yum automatically resolves the dependencies for us and will download and install any additional packages from our configured repositories.
If you’d like further information on using yum, see our 25 yum command examples here.
Install RPM File With DNF
DNF is the next version of Yum, it’s another package manager for working with RPM files. DNF syntax is fairly similar to the Yum command, as shown below we can install our RPM file in the same way.
As of Fedora 22 DNF has replaced Yum, so that’s useful to be aware of although it has not yet made its way into RHEL/CentOS where Yum is still the king.
If you’d like further information on using dnf, see our 25 dnf command examples here.
Install RPM File With RPM Command
For comparison, we can also use the rpm command with the -i option to install a specified RPM package. This is not however capable of automatically resolving the dependencies for us, as shown by the errors below we would have to go out and manually download these additional packages, which then themselves may have further package dependencies. This situation is commonly referred to as dependency hell, and is something package managers help us avoid.
How To Download RPM Files
Usually RPM files will be downloaded from some random page on the Internet, however it’s possible to also download an RPM file from a repository directly using the yumdownloader command. Simply specify the package that you want to download after yumdownloader and it will download a copy of the RPM file that is used to install the package into the current working directory.
This can be a useful way to quickly download a RPM package file using yum to copy elsewhere, perhaps to a Linux server that is in an isolated network without Internet access for example.
Summary
We have covered three different methods for installing RPM files in Linux here. While using Yum/DNF are the preferred options for the reasons mentioned such as automatic dependency resolution, we can also use the rpm command with the -i option to install an RPM file in supported Linux distributions.
Источник
ИТ База знаний
Курс по Asterisk
Полезно
— Узнать IP — адрес компьютера в интернете
— Онлайн генератор устойчивых паролей
— Онлайн калькулятор подсетей
— Калькулятор инсталляции IP — АТС Asterisk
— Руководство администратора FreePBX на русском языке
— Руководство администратора Cisco UCM/CME на русском языке
— Руководство администратора по Linux/Unix
Навигация
Серверные решения
Телефония
FreePBX и Asterisk
Настройка программных телефонов
Корпоративные сети
Протоколы и стандарты
RPM — установка и использование в Linux
Вам пакет нужен? Нет, я со своим.
RPM (Red Hat Package Manager) — это наиболее популярная утилита управления пакетами для Linux систем на базе Red Hat, таких как (RHEL, CentOS и Fedora). Она используется для установки, удаления, обновления, запроса и проверки пакетов программного обеспечения. Пакет состоит из архива файлов и информации о пакете, включая имя, версию и описание. Формат файлов также называется RPM.
Мини — курс по виртуализации
Знакомство с VMware vSphere 7 и технологией виртуализации в авторском мини — курсе от Михаила Якобсена
Есть несколько способов откуда можно взять пакеты RPM: CD/DVD с программным обеспечением, CentOS Mirror, RedHat (нужен аккаунт) или любые открытые сайты репозитория.
В RPM используется несколько основных режимов команд: Install (используется для установки любого пакета RPM), Remove (используется для удаления, стирания или деинсталляции пакета), Upgrade (используется для обновления существующего пакета), Query (используется для запроса пакета) и Verify (используется для проверки пакетов RPM).
Рассмотрим это на примере. У нас есть пакет, и теперь посмотрим, что мы можем с ним делать.
Установка
Как узнать информацию о пакете RPM без установки?
После того, как мы скачали пакет мы хотим узнать информацию о пакете перед установкой. Мы можем использовать -qipoption (запрос информации о пакете), чтобы вывести информацию о пакете.
Как установить RPM пакет?
Мы можем использовать параметр -ivh для установки определенного пакета, как показано ниже.
Как проверить установленный пакет RPM?
Мы можем использовать параметр -q с именем пакета, и он покажет, установлен ли пакет или нет.
Как вывести список всех файлов для определенного установленного пакета RPM?
Мы можем перечислить все файлы установленных пакетов rpm, используя опцию -ql с командой rpm.
Как вывести список недавно установленных пакетов RPM?
Мы можем использовать параметр -qa с параметром —last, в котором будут перечислены все недавно установленные пакеты rpm.
Как установить RPM пакет без зависимостей?
Мы можем использовать параметры -ivh с параметром —nodeps для проверки отсутствия зависимостей, чтобы установить конкретный пакет без зависимостей, как показано ниже.
Как заменить установленный пакет RPM?
Мы можем использовать параметры -ivh –replacepkgs для замены установленного пакета.
Удаление
Как удалить пакет RPM?
Мы можем использовать параметр -e для удаления определенного пакета, установленного без зависимостей. Обратите внимание, что удаление определенного пакета может нарушить работу других приложений.
Обновление
Как обновить установленный пакет RPM?
Для обновления пакета мы используем параметры -Uvh
Запрос
Как запросить все установленные пакеты?
Мы можем использовать параметры -a вместе с q для запроса всех установленных пакетов на сервере.
Как запросить конкретный пакет?
Мы можем использовать команду grep, чтобы узнать, установлен ли конкретный пакет или нет.
Как запросить файл, который принадлежит пакету RPM?
Чтобы узнать к какому пакету RPM относится файл /usr/lib64/libGeoIP.so.1.5.0. используем следующую команду.
Проверка
Как получить информацию для конкретного пакета?
Мы можем использовать параметры -i вместе с q, чтобы получить информацию для конкретного пакета, как показано ниже.
Как проверить RPM пакет?
Мы можем проверить пакет, сравнив информацию об установленных файлах пакета с базой данных rpm, используя опцию -Vp.
Как проверить все пакеты RPM?
Мы можем проверить все установленные пакеты rpm, используя опцию -Va
Онлайн курс по Linux
Мы собрали концентрат самых востребованных знаний, которые позволят тебе начать карьеру администратора Linux, расширить текущие знания и сделать уверенный шаг к DevOps
Полезно?
Почему?
😪 Мы тщательно прорабатываем каждый фидбек и отвечаем по итогам анализа. Напишите, пожалуйста, как мы сможем улучшить эту статью.
😍 Полезные IT – статьи от экспертов раз в неделю у вас в почте. Укажите свою дату рождения и мы не забудем поздравить вас.
Источник