- Установка rpm пакетов в Linux
- Что такое RPM?
- Установка RPM пакетов в Linux
- Установка RPM файла в GUI
- Выводы
- How to Install an RPM File On Linux OS (CentOS, RHEL, & Fedora)
- Step 1: Download RPM Installation File
- Step 2: Install RPM File on Linux
- Install RPM File Using RPM Command
- Install RPM File with Yum
- Install RPM on Fedora
- Remove RPM Package
- Download RPM Packages from the Repository
- rpm(8) — Linux man page
- Synopsis
- Querying and Verifying Packages:
- Installing, Upgrading, and Removing Packages:
- Miscellaneous:
- select-options
- query-options
- verify-options
- install-options
- Description
- General Options
- Install and Upgrade Options
- Erase Options
- Query Options
- Package Selection Options:
- Package Query Options:
- Verify Options
- Digital Signature and Digest Verification
- Signing a Package
- Using Gpg to Sign Packages
- Rebuild Database Options
- Miscellaneous Commands
- Ftp/Http Options
- Legacy Issues
- Executing rpmbuild
Установка rpm пакетов в Linux
Рано или поздно нам приходится устанавливать программное обеспечение не из официальных репозиториев. Там есть далеко не все пакеты, и не всегда есть самые новые версии, только что вышедших программ. Очень часто разработчики размещают на своем официальном сайте пакеты для самых популярных дистрибутивов. Обычно это deb и rpm.
Последний встречается немного реже, но если вы используете дистрибутив на базе Red Hat Enterprice Linux, вам нужен именно этот формат пакетов. Также в сети часто можно найти библиотеки и другие компоненты, которых нет в репозиториях в виде пакетов. Раньше мы уже рассматривали установку deb пакетов в Ubuntu. А в этой статье будет подробно разобрана установка rpm пакетов в linux.
Что такое RPM?
RPM или RPM Package Manager — это пакетный менеджер, используемый в дистрибутивах Linux, основанных на Red Hat. Такое же название имеет формат файлов этого пакетного менеджера.
Этот формат не очень сильно отличается от того же самого Deb. Вы можете посмотреть их детальное сравнение в статье что лучше *.deb или *.rpm. Здесь же, только отмечу, что файл rpm — это обычный cpio архив, в котором содержатся сами файлы программы, а также метаданные, описывающие куда их нужно устанавливать. База всех установленных пакетов находится в каталоге /var/lib/rpm. Из особенностей можно отметить, что rpm не поддерживает рекомендованные пакеты, а также зависимости формата или-или.
Для управления пакетами, так же как и в Debian-системах, здесь существует консольная, низкоуровневая утилита с одноименным названием — rpm. Ее мы и будем рассматривать дальше в статье. В разных системах используются разные пакетные менеджеры, например в Red Hat используется Yum, в Fedora — DNF, а в OpenSUSE — zypper, но во всех этих системах будет работать утилита rpm.
Установка RPM пакетов в Linux
Давайте сначала рассмотрим синтаксис самой утилиты rpm:
$ rpm -режим опции пакет
Утилита может работать в одном из режимов:
- -q, —query — запрос, получение информации;
- -i, —install — установка;
- -V, —verify — проверка пакетов;
- -U, —upgrade — обновление;
- -e, —erase — удаление.
Рассмотрим только самые интересные опции программы, которые понадобятся нам в этой статье:
- -v — показать подробную информацию;
- —vv — выводить отладочную информацию;
- —quiet — выводить как можно меньше информации;
- -h — выводить статус-бар;
- —percent — выводить информацию в процентах о процессе распаковки;
- —force — выполнять действие принудительно;
- —nodeps — не проверять зависимости;
- —replacefiles — заменять все старые файлы на новые без предупреждений;
- -i — получить информацию о пакете;
- -l — список файлов пакета;
- -R — вывести пакеты, от которых зависит этот пакет;
Теперь, когда вы уже имеете представление как работать с этой утилитой, может быть рассмотрена установка rpm пакета в Linux. Самая простая команда установки будет выглядеть вот так:
sudo rpm -i имя_пакета.rpm
Для работы с командной текущей директорией должна быть папка с пакетом. Здесь мы устанавливаем режим установки и передаем файл пакета. При успешной установке утилита не выведет ничего, если произойдет ошибка, вы об этом узнаете.
Для того чтобы посмотреть более подробную информацию в процессе установки используйте опцию -v:
sudo rpm -iv имя_пакета.rpm
Также вы можете включить отображение статус бара в процессе установки:
sudo rpm -ivh имя_пакета.rpm
Чтобы проверить установлен ли пакет, нам уже нужно использовать режим запроса:
sudo rpm -q имя_пакета
Также сразу можно удалить пакет, если он не нужен:
sudo rpm -e имя_пакета
Но у rpm так же как и у dpkg, есть один существенный недостаток. Программа не может разрешать зависимости. В случае отсутствия нужного пакета в системе, вы просто получите сообщение об ошибке и пакет не установится.
Для автоматической загрузки зависимостей во время выполнения установки rpm linux нужно использовать пакетный менеджер дистрибутива. Рассмотрим несколько команд для самых популярных RPM дистрибутивов. В RedHat и других дистрибутивах, использующих Yum используйте такую команду:
sudo yum —nogpgcheck localinstall имя_пакета.rpm
Первая опция отключает проверку GPG ключа, а вторая говорит, что мы будем выполнять установку локального пакета. В Fedora, с помощью dnf все делается еще проще:
sudo dnf install имя_пакета.rpm
Пакетный менеджер Zypper и OpenSUSE справляются не хуже:
sudo zypper install имя_пакета.rpm
Вот так очень просто выполняется установка rpm с зависимостями. Но не всем нравится работать в консоли, многие новые пользователи хотят использовать графический интерфейс для решения всех задач, в том числе и этой. Дальше мы рассмотрим несколько таких утилит.
Установка RPM файла в GUI
Если вы используете OpenSUSE, то это делается очень просто. Универсальный конфигуратор системы YaST, кроме всего прочего позволяет установить rpm пакеты. Вы можете сделать это с помощью файлового менеджера, выбрав пункт контекстного меню для файла открыть с помощью Yast или выполнив команду:
yast2 -i имя_пакета.rpm
В Fedora для тех же целей вы можете использовать менеджер приложений дистрибутива. Раньше было еще несколько универсальных утилит для решения этой задачи, но сейчас они уже все устарели.
Выводы
Теперь вы знаете как выполняется установка rpm файла в Linux. На самом деле это очень просто и даже существует не только один способ, а целых несколько. Хотя графических утилит здесь немного меньше чем в Ubuntu. Но консольных утилит полностью хватает. Если у вас остались вопросы, спрашивайте в комментариях!
How to Install an RPM File On Linux OS (CentOS, RHEL, & Fedora)
Home » SysAdmin » How to Install an RPM File On Linux OS (CentOS, RHEL, & Fedora)
While working in Linux, you may have seen downloadable files with the .rpm extension. Rpm files are designed to be downloaded and installed independently, outside of a software repository.
This guide will show you how to install a .rpm file to your Linux CentOS or Fedora system.
Note: RPM Package Manager (RPM) is a free and open-source package management system for installing, uninstalling and managing software packages in Linux.
- A user account with sudo privileges
- Access to a terminal window / command line (Menu > applications > utilities > terminal, Ctrl-Alt-F2)
- RPM, DNF, & YUM Package Managers (all included by default)
Step 1: Download RPM Installation File
Typically, a web browser is used to locate and download a .rpm file. However, if a browser is not available you can still download a file if you know where it’s located.
You may need to install a software tool called wget .
To install wget in CentOS, enter the following in a terminal window:
To install wget in Fedora, enter the following:
Now, you can use the wget command to download the .rpm file you want. Enter the following:
The system should reach out to the website and download the file to your current working directory.
Note: You can look up the address of a particular .rpm file in a web browser on another system. Also, this is a handy way to install more recent software versions or special non-standard software. Also, take care when installing software packages! Make sure you trust the source before you install. Usually, a developer will include a verification method to make sure you’re getting authentic software.
Step 2: Install RPM File on Linux
Install RPM File Using RPM Command
To install a .rpm package in CentOS Linux, enter the following:
The -i switch tells the package manager you want to install the file.
More information on the RPM installer can be found in the RPM documentation.
Install RPM File with Yum
Alternately, you can use the yum package manager to install .rpm files.
Enter the following:
The localinstall option instructions yum to look at your current working directory for the installation file.
Note: YUM stands for Yellowdog Updater Modified. Normally, yum looks to your enabled software repositories for new software packages to install. More recent verbiage suggests using install instead of localinstall, but it’s up to you.
Install RPM on Fedora
To install an .rpm package on Fedora Linux, enter the following:
Just as in CentOS, the -i switch tells RPM to install the software.
Another method is to use the dnf utility to install the package:
Unlike many Linux tools, DNF is not a set of initials. It is merely the next evolution of the yum package manager.
Remove RPM Package
The RPM installer can be used to remove (or uninstall) a software package.
Enter the following into a terminal window:
The -e option instructs RPM to erase the software. Check RPM Dependencies
So far, this guide assumes the software either doesn’t have dependencies or already has them installed.
To check the .rpm file for dependencies using the following command:
The system should list all the dependencies:
- -q – This option tells RPM to query the file
- -p – This option lets you specify the target package to query
- -R – This lists the requirements for the package
If there are any missing dependencies, you can install them from the standard repositories using yum or dnf. If your software requires other non-standard software, it will often be noted in the installation instructions.
Download RPM Packages from the Repository
One exciting feature of the yum package manager is that it allows you to download .rpm files directly from the repository. This might be helpful if you have limited bandwidth, or want to copy a single downloaded file between systems. It could also help if you have intermittent internet access, and you don’t want to spend time waiting for your installer to finish.
To download a .rpm file from the repositories, enter the following:
If you wanted to download the files for Apache, for instance, you’d replace packagename with httpd. You can then install the file as above.
Note: In Linux, administrators find it helpful to have a single tool to manage software. That tool – called a package manager – can install software, keep track of software requirements, and track updates and patches. Package managers also work with repositories, which are secure and standardized libraries of commonly-used and well-supported applications. If you had to install wget in Step 1, that’s an example of installing from a repository.
In this tutorial, we covered three different options for installing RPM files on Linux.
As with most Linux software, your default package manager makes it simple to track installations, updates, and prerequisites.
rpm(8) — Linux man page
Synopsis
Querying and Verifying Packages:
Installing, Upgrading, and Removing Packages:
Miscellaneous:
select-options
query-options
verify-options
install-options
Description
rpm is a powerful Package Manager, which can be used to build, install, query, verify, update, and erase individual software packages. A package consists of an archive of files and meta-data used to install and erase the archive files. The meta-data includes helper scripts, file attributes, and descriptive information about the package. Packages come in two varieties: binary packages, used to encapsulate software to be installed, and source packages, containing the source code and recipe necessary to produce binary packages.
One of the following basic modes must be selected: Query, Verify, Signature Check, Install/Upgrade/Freshen, Uninstall, Initialize Database, Rebuild Database, Resign, Add Signature, Set Owners/Groups, Show Querytags, and Show Configuration.
General Options
These options can be used in all the different modes. -?, —help Print a longer usage message then normal. —version Print a single line containing the version number of rpm being used. —quiet Print as little as possible — normally only error messages will be displayed. -v Print verbose information — normally routine progress messages will be displayed. -vv Print lots of ugly debugging information. —rcfile FILELIST Each of the files in the colon separated FILELIST is read sequentially by rpm for configuration information. Only the first file in the list must exist, and tildes will be expanded to the value of $HOME. The default FILELIST is /usr/lib/rpm/rpmrc:/usr/lib/rpm/redhat/rpmrc:/etc/rpmrc:
/.rpmrc. —pipe CMD Pipes the output of rpm to the command CMD. —dbpath DIRECTORY Use the database in DIRECTORY rather than the default path /var/lib/rpm —root DIRECTORY Use the file system tree rooted at DIRECTORY for all operations. Note that this means the database within DIRECTORY will be used for dependency checks and any scriptlet(s) (e.g. %post if installing, or %prep if building, a package) will be run after a chroot(2) to DIRECTORY. -D, —define=’MACRO EXPR‘ Defines MACRO with value EXPR. -E, —eval=’EXPR‘ Prints macro expansion of EXPR.
Install and Upgrade Options
In these options, PACKAGE_FILE can be either rpm binary file or ASCII package manifest (see PACKAGE SELECTION OPTIONS), and may be specified as an ftp or http URL, in which case the package will be downloaded before being installed. See FTP/HTTP OPTIONS for information on rpm‘s internal ftp and http client support.
The general form of an rpm install command is
This installs a new package.
The general form of an rpm upgrade command is
This upgrades or installs the package currently installed to a newer version. This is the same as install, except all other version(s) of the package are removed after the new package is installed.
This will upgrade packages, but only ones for which an earlier version is installed. —aid Add suggested packages to the transaction set when needed. —allfiles Installs or upgrades all the missingok files in the package, regardless if they exist. —badreloc Used with —relocate, permit relocations on all file paths, not just those OLDPATH‘s included in the binary package relocation hint(s). —excludepath OLDPATH Don’t install files whose name begins with OLDPATH. —excludedocs Don’t install any files which are marked as documentation (which includes man pages and texinfo documents). —force Same as using —replacepkgs, —replacefiles, and —oldpackage. -h, —hash Print 50 hash marks as the package archive is unpacked. Use with -v|—verbose for a nicer display. —ignoresize Don’t check mount file systems for sufficient disk space before installing this package. —ignorearch Allow installation or upgrading even if the architectures of the binary package and host don’t match. —ignoreos Allow installation or upgrading even if the operating systems of the binary package and host don’t match. —includedocs Install documentation files. This is the default behavior. —justdb Update only the database, not the filesystem. —nodigest Don’t verify package or header digests when reading. —nomanifest Don’t process non-package files as manifests. —nosignature Don’t verify package or header signatures when reading. —nodeps Don’t do a dependency check before installing or upgrading a package. —nosuggest Don’t suggest package(s) that provide a missing dependency. —noorder Don’t reorder the packages for an install. The list of packages would normally be reordered to satisfy dependencies. —noscripts —nopre —nopost —nopreun —nopostun Don’t execute the scriptlet of the same name. The —noscripts option is equivalent to
—nopre —nopost —nopreun
and turns off the execution of the corresponding %pre, %post, %preun, and %postun scriptlet(s). —notriggers —notriggerin —notriggerun —notriggerpostun Don’t execute any trigger scriptlet of the named type. The —notriggers option
is equivalent to
—notriggerin —notriggerun —notriggerpostun
and turns off execution of the corresponding %triggerin, %triggerun, and %triggerpostun scriptlet(s). —oldpackage Allow an upgrade to replace a newer package with an older one. —percent Print percentages as files are unpacked from the package archive. This is intended to make rpm easy to run from other tools. —prefix NEWPATH For relocatable binary packages, translate all file paths that start with the installation prefix in the package relocation hint(s) to NEWPATH. —relocate OLDPATH=NEWPATH For relocatable binary packages, translate all file paths that start with OLDPATH in the package relocation hint(s) to NEWPATH. This option can be used repeatedly if several OLDPATH‘s in the package are to be relocated. —replacefiles Install the packages even if they replace files from other, already installed, packages. —replacepkgs Install the packages even if some of them are already installed on this system. —test Do not install the package, simply check for and report potential conflicts.
Erase Options
The general form of an rpm erase command is
The following options may also be used: —allmatches Remove all versions of the package which match PACKAGE_NAME. Normally an error is issued if PACKAGE_NAME matches multiple packages. —nodeps Don’t check dependencies before uninstalling the packages. —noscripts —nopreun —nopostun Don’t execute the scriptlet of the same name. The —noscripts option during package erase is equivalent
and turns off the execution of the corresponding %preun, and %postun scriptlet(s). —notriggers —notriggerun —notriggerpostun Don’t execute any trigger scriptlet of the named type. The —notriggers option
is equivalent to
and turns off execution of the corresponding %triggerun, and %triggerpostun scriptlet(s). —test Don’t really uninstall anything, just go through the motions. Useful in conjunction with the -vv option for debugging.
Query Options
The general form of an rpm query command is
You may specify the format that package information should be printed in. To do this, you use the
option, followed by the QUERYFMT format string. Query formats are modified versions of the standard printf(3) formatting. The format is made up of static strings (which may include standard C character escapes for newlines, tabs, and other special characters) and printf(3) type formatters. As rpm already knows the type to print, the type specifier must be omitted however, and replaced by the name of the header tag to be printed, enclosed by <> characters. Tag names are case insensitive, and the leading RPMTAG_ portion of the tag name may be omitted as well.
Alternate output formats may be requested by following the tag with :typetag. Currently, the following types are supported: :armor Wrap a public key in ASCII armor. :arraysize Display number of elements in array tags. :base64 Encode binary data using base64. :date Use strftime(3) «%c» format. :day Use strftime(3) «%a %b %d %Y» format. :depflags Format dependency comparison operator. :deptype Format dependency type. :fflags Format file flags. :fstate Format file state. :hex Format in hexadecimal. :octal Format in octal. :perms Format file permissions. :pgpsig Display signature fingerprint and time. :shescape Escape single quotes for use in a script. :triggertype Display trigger suffix. :vflags File verification flags. :xml Wrap data in simple xml markup.
For example, to print only the names of the packages queried, you could use % as the format string. To print the packages name and distribution information in two columns, you could use %-30
There are two subsets of options for querying: package selection, and information selection.
Package Selection Options:
Package Query Options:
Verify Options
The general form of an rpm verify command is
Verifying a package compares information about the installed files in the package with information about the files taken from the package metadata stored in the rpm database. Among other things, verifying compares the size, digest, permissions, type, owner and group of each file. Any discrepancies are displayed. Files that were not installed from the package, for example, documentation files excluded on installation using the «—excludedocs» option, will be silently ignored.
The package selection options are the same as for package querying (including package manifest files as arguments). Other options unique to verify mode are: —nodeps Don’t verify dependencies of packages. —nodigest Don’t verify package or header digests when reading. —nofiles Don’t verify any attributes of package files. —noscripts Don’t execute the %verifyscript scriptlet (if any). —nosignature Don’t verify package or header signatures when reading. —nolinkto —nofiledigest (formerly —nomd5) —nosize —nouser —nogroup —nomtime —nomode —nordev Don’t verify the corresponding file attribute.
The format of the output is a string of 8 characters, a possible attribute marker: from the package header, followed by the file name. Each of the 8 characters denotes the result of a comparison of attribute(s) of the file to the value of those attribute(s) recorded in the database. A single «.» (period) means the test passed, while a single «?» (question mark) indicates the test could not be performed (e.g. file permissions prevent reading). Otherwise, the (mnemonically emBoldened) character denotes failure of the corresponding —verify test:
Digital Signature and Digest Verification
The general forms of rpm digital signature commands are
The —checksig option checks all the digests and signatures contained in PACKAGE_FILE to ensure the integrity and origin of the package. Note that signatures are now verified whenever a package is read, and —checksig is useful to verify all of the digests and signatures associated with a package.
Digital signatures cannot be verified without a public key. An ASCII armored public key can be added to the rpm database using —import. An imported public key is carried in a header, and key ring management is performed exactly like package management. For example, all currently imported public keys can be displayed by:
rpm -qa gpg-pubkey*
Details about a specific public key, when imported, can be displayed by querying. Here’s information about the Red Hat GPG/DSA key:
rpm -qi gpg-pubkey-db42a60e
Finally, public keys can be erased after importing just like packages. Here’s how to remove the Red Hat GPG/DSA key
rpm -e gpg-pubkey-db42a60e
Signing a Package
Both of the —addsign and —resign options generate and insert new signatures for each package PACKAGE_FILE given, replacing any existing signatures. There are two options for historical reasons, there is no difference in behavior currently.
Using Gpg to Sign Packages
In order to sign packages using GPG, rpm must be configured to run GPG and be able to find a key ring with the appropriate keys. By default, rpm uses the same conventions as GPG to find key rings, namely the $GNUPGHOME environment variable. If your key rings are not located where GPG expects them to be, you will need to configure the macro %_gpg_path to be the location of the GPG key rings to use.
For compatibility with older versions of GPG, PGP, and rpm, only V3 OpenPGP signature packets should be configured. Either DSA or RSA verification algorithms can be used, but DSA is preferred.
If you want to be able to sign packages you create yourself, you also need to create your own public and secret key pair (see the GPG manual). You will also need to configure the rpm macros %_signature The signature type. Right now only gpg and pgp are supported. %_gpg_name The name of the «user» whose key you wish to use to sign your packages.
For example, to be able to use GPG to sign packages as the user «John Doe « from the key rings located in /etc/rpm/.gpg using the executable /usr/bin/gpg you would include in a macro configuration file. Use /etc/rpm/macros for per-system configuration and
/.rpmmacros for per-user configuration. Typically it’s sufficient to set just %_gpg_name.
Rebuild Database Options
The general form of an rpm rebuild database command is
Use —initdb to create a new database if one doesn’t already exist (existing database is not overwritten), use —rebuilddb to rebuild the database indices from the installed package headers.
Miscellaneous Commands
Ftp/Http Options
rpm can act as an FTP and/or HTTP client so that packages can be queried or installed from the internet. Package files for install, upgrade, and query operations may be specified as an ftp or http style URL:
If the :PASSWORD portion is omitted, the password will be prompted for (once per user/hostname pair). If both the user and password are omitted, anonymous ftp is used. In all cases, passive (PASV) ftp transfers are performed.
rpm allows the following options to be used with ftp URLs: —ftpproxy HOST The host HOST will be used as a proxy server for all ftp transfers, which allows users to ftp through firewall machines which use proxy systems. This option may also be specified by configuring the macro %_ftpproxy. —ftpport PORT The TCP PORT number to use for the ftp connection on the proxy ftp server instead of the default port. This option may also be specified by configuring the macro %_ftpport.
rpm allows the following options to be used with http URLs: —httpproxy HOST The host HOST will be used as a proxy server for all http transfers. This option may also be specified by configuring the macro %_httpproxy. —httpport PORT The TCP PORT number to use for the http connection on the proxy http server instead of the default port. This option may also be specified by configuring the macro %_httpport.
Legacy Issues
Executing rpmbuild
The build modes of rpm are now resident in the /usr/bin/rpmbuild executable. Install the package containing rpmbuild (usually rpm-build) and see rpmbuild(8) for documentation of all the rpm build modes.