- Pacman
- Содержание
- Общее
- Использование
- Установка и удаление пакетов
- Обновление системы
- Получение списка установленных пакетов для быстрого восстановления системы
- Запросы к базе данных пакетов
- Одновременный поиск в репозитории и среди установленных пакетов
- Другое использование
- Настройка
- Основные опции
- Репозитории
- pacman/Package signing
- Contents
- Setup
- Configuring pacman
- Initializing the keyring
- Managing the keyring
- Verifying the master keys
- Adding developer keys
- Adding unofficial keys
- Debugging with gpg
- Tips and tricks
- Upgrade system regularly
- Update system time regularly
- Troubleshooting
- Invalid signature errors
- Removing packages from cache
- Resetting all the keys
- Disabling signature checking
- Cannot import keys
- Upgrade the system
- Change keyserver
- Clean cached packages
- Signature is unknown trust
Pacman
Содержание
Общее
Arch Linux использует менеджер пакетов Pacman, который соединяет в себе простой формат бинарных пакетов и простую в использовании систему сборки, позволяющую пользователям с легкостью управлять и настраивать под себя пакеты, вне зависимости от того, официальные ли они или собранные пользователем. Система репозиториев позволяет пользователям создавать и поддерживать собственные репозитории с собранными пакетами, что способствует росту сообщества.
Pacman может держать систему в новейшем состоянии, синхронизируя пакеты с главным сервером, тем самым позволяя сознательному администратору поддерживать систему. Клиент-серверная модель позволяет скачивать/устанавливать пакеты одной командой со всеми требуемыми зависимостями (похоже на apt-get от Debian).
Pacman был написан на языке C и поэтому он быстрый, легкий. Он использует .tar.gz формат пакетов, эти пакеты извлекаются быстрее.
Использование
Pacman является универсальным менеджером пакетов, способным скачивать, устанавливать и обновлять пакеты и из репозитория, и собственные локальные, удалять и искать их. Вам только необходимо знать, какой ключ используется функцией для желаемых действий. Вот несколько наиболее часто используемых:
Установка и удаление пакетов
Перед установкой и обновлением пакетов полезно синхронизировать базу данных локально установленных пакетов с удалёнными репозиториями
Для того чтобы установить или обновить один пакет или группу пакетов (включая зависимости), используйте следующую команду:
Иногда пакет имеет несколько версий в разных репозиториях (например в extra и testing). Вы можете указать, какой именно вы хотите установить:
Вы можете совмещать параметры, например, эта команда синхронизирует базы данных и установит пакет:
Удалить пакет (оставляя все зависимости в системе):
Удалить пакет со всеми зависимостями, не используемыми другими установленными пакетами:
По умолчанию Pacman создает резервные копии конфигурационных файлов удаляемых приложений с помощью добавления к ним расширения *. pacsave. Если вы хотите удалить эти файлы при удалении соответствующего пакета (подсказка: это операция называется purging в Debian-системах), вы можете использовать:
Конечно, это может быть дополнено -s, чтобы также удалить ненужные теперь зависимости. Таким образом, команда полностью удалит пакет, его конфигурации и все зависимости, которые больше не нужны:
Обновление системы
Pacman может обновить все пакеты системы одной командой. Количество пакетов зависит от того, насколько ваша система современна.
NB: вы можете синхронизировать базы данных репозиториев И обновить все установленные пакеты одной командой:
Хорошо выполнять эту команду каждые несколько дней.
Получение списка установленных пакетов для быстрого восстановления системы
Если ваша система упала и ее сложно восстановить то неплохо бы иметь список пакетов которые были установлены в ней.
Сохранить в файл pkglist список пакетов установленных в системе:
Сохраните этот файл на флешке или еще где-нибудь.
Если вдруг с вашей системой случится что-либо неприятное то установленые пакеты легко можно восстановить:
Запросы к базе данных пакетов
- Поиск пакетов в репозиториях, вы можете указать только часть названия:
- Поиск среди установленных пакетов:
- Вывод информации о пакете:
- Вывод списка файлов пакета:
- Какой пакет является владельцем файла?
- Перечислите все пакеты, больше не требуемые как зависимости(сироты):
- Удалить всех сирот: (Проверьте сначала вывод команды pacman -Qdt.)
Одновременный поиск в репозитории и среди установленных пакетов
Вы можете использовать следующий bash скрипт в качестве эквивалента для одновременного вызова pacman -Ss foo и pacman -Qs foo, для того чтобы узнать, какие из пакетов в выводе установлены на вашей системе. Последние будут помечены звёздочкой.
Сохраните этот скрипт в каталоге, включенном в переменную PATH (например,
/bin/), и назовите его pacsearch. Сделайте его исполняемым с помощью
Теперь если вы напишете, например:
вывод может выглядеть так:
В этом случае вы узнаете, что ни один из вышеперечисленных пакетов (кроме самого qt) на вашей системе не установлен.
NB1: был добавлен запрос на flyspray с предложением интегрировать вышеуказанную функциональность в сам pacman, чтобы ‘грязные’ хитрости bash стали стать ненужными с последующими версиями pacman.
NB2: вы можете изменить этот bash скрипт с помощью этого wiki, для того чтобы установленные пакеты были выделены различными цветами в выводе.
Другое использование
- Скачать пакет, но не устанавливать его:
- Установить локальный пакет (не из репозитория):
Вы можете ввести ссылку:
- Очистка кэша pacman`а (/var/cache/pacman/pkg):
- Для того, чтобы переустановить все пакеты в вашей системе (которые доступны в репозитории):
Для более детальной информацией о возможных ключах обратитесь к pacman —help или man pacman.
Настройка
Настройки pacman`a находятся в /etc/pacman.conf . Важными секциями являются:
Основные опции
Основные опции находятся в секции [options]. Есть одна полезная опция IgnorePkg. Например, если вы изменяли или накладывали патч на пакет, добавление его в IgnorePkg укажет pacman’у не обновлять его при выходе следующей версии пакета. Но pacman всё же предупредит вас о том, что доступна более свежая версия, так что в итоге вы можете обновить ваш изменённый пакет. Опция также полезна для БОЛЬШИХ пакетов (например, openoffice-base), если вы хотите избежать скачивания и обновления всего пакета каждый раз, когда в репозитории появляется маленькое изменение. Поскольку pacman всё равно предупредит вас о последней версии, вы можете обновить пакет вручную.
Репозитории
В этой секции вы указываете используемые репозитории. Они могут быть указаны напрямую или как файл, содержащий список серверов. Последнее удобно для официальных репозиториев, имеющих множество зеркал.
За более подробной информацией обратитесь к man pacman.
Источник
pacman/Package signing
To determine if packages are authentic, pacman uses GnuPG keys in a web of trust model. The current Master Signing Keys are found here. At least three of these Master Signing Keys are used to sign the Developer’s and Trusted User’s own keys. They are then used to sign their packages. Each user also has a unique PGP key, which is generated when you configure pacman-key. It is this web of trust that links the user’s key to the master keys.
Examples of webs of trust:
- Custom packages: Packages made and signed with a local key.
- Unofficial packages: Packages made and signed by a developer. Then, a local key was used to sign the developer’s key.
- Official packages: Packages made and signed by a developer. The developer’s key was signed by the Arch Linux master keys. You used your key to sign the master keys, and you trust them to vouch for developers.
Contents
Setup
Configuring pacman
The SigLevel option in /etc/pacman.conf determines the level of trust required to install a package. For a detailed explanation of SigLevel , see pacman.conf(5) § PACKAGE AND DATABASE SIGNATURE CHECKING and the file comments. One can set signature checking globally or per repository. If SigLevel is set globally in the [options] section, all packages will then require signing. Any packages you build will then need to be signed using makepkg.
The default configuration will only support the installation of packages signed by trusted keys:
TrustedOnly is a default compiled-in pacman parameter. The default configuration is identical to using the global option of:
The above can be achieved too on a repository level further below in the configuration, e.g.:
explicitly adds signature checking for the packages of the repository, but does not require the database to be signed. Optional here would turn off a global Required for this repository.
Initializing the keyring
To initialize the pacman keyring run:
Initializing the keyring requires entropy. To generate entropy, move your mouse around, press random characters on the keyboard, or run some disk-based activity (for example in another console running ls -R / or find / -name foo or dd if=/dev/sda8 of=/dev/tty7 ). If your system does not already have sufficient entropy, this step may take hours; if you actively generate entropy, it will complete much more quickly.
The randomness created is used to initialize the keyring ( /etc/pacman.d/gnupg ) and the GPG signing key of your system.
Managing the keyring
Verifying the master keys
The initial setup of keys is achieved using:
Take time to verify the Master Signing Keys when prompted as these are used to co-sign (and therefore trust) all other packager’s keys.
PGP keys are too large (2048 bits or more) for humans to work with, so they are usually hashed to create a 40-hex-digit fingerprint which can be used to check by hand that two keys are the same. The last eight digits of the fingerprint serve as a name for the key known as the ‘(short) key ID’ (the last sixteen digits of the fingerprint would be the ‘long key ID’).
Adding developer keys
The official developer and Trusted Users (TU) keys are signed by the master keys, so you do not need to use pacman-key to sign them yourself. Whenever pacman encounters a key it does not recognize, it will prompt you to download it from a keyserver configured in /etc/pacman.d/gnupg/gpg.conf (or by using the —keyserver option on the command line). Wikipedia maintains a list of keyservers.
Once you have downloaded a developer key, you will not have to download it again, and it can be used to verify any other packages signed by that developer.
Adding unofficial keys
This article or section needs expansion.
This method can be utilized to add a key to the pacman keyring, or to enable signed unofficial user repositories.
First, get the key ID ( keyid ) from its owner. Then add it to the keyring using one of the two methods:
- If the key is found on a keyserver, import it with:
- If otherwise a link to a keyfile is provided, download it and then run:
It is recommended to verify the fingerprint, as with any master key or any other key you are going to sign:
Finally, you must locally sign the imported key:
You now trust this key to sign packages.
Debugging with gpg
For debugging purposes, you can access pacman’s keyring directly with gpg, e.g.:
Tips and tricks
Upgrade system regularly
Upgrading the system regularly via pacman#Upgrading packages prevents most signing errors. If delay is unavoidable and system upgrade gets delayed for an extended period, manually sync the package database and upgrade the archlinux-keyring package before system upgrade:
This command is not considered a partial upgrade since it syncs the package database and upgrades the keyring package first. Both must be processed just before starting system upgrade to ensure signatures of all upgraded packages can be properly verified.
Update system time regularly
When the system time is faulty, signing keys could be considered expired (or invalid) and signature checks on packages will fail. Synchronize the system clock regularly by using the Network Time Protocol daemon.
Troubleshooting
Invalid signature errors
pacman-key depends on system time. If your system clock is not synchronized, system installation/upgrade may fail with:
If using ntpd, correct the system time (as root) with ntpd -qg followed by hwclock -w .
Other NTP clients can be used. See time synchronization.
If correction of the system clock does not resolve the failure, try one of the following approaches:
Removing packages from cache
Some packages could be corrupted or may be unsigned, causing failure. Remove each offending package from the system cache rm /var/cache/pacman/pkg/pkgname so it gets freshly downloaded, or clear the entire cache.
Resetting all the keys
Remove or reset all the keys installed in your system by removing the /etc/pacman.d/gnupg folder (as root) and by rerunning pacman-key —init followed by pacman-key —populate archlinux to re-add the default keys.
Disabling signature checking
If you are not concerned about package signing, you can disable PGP signature checking completely. Edit /etc/pacman.conf and uncomment the following line under [options] :
You need to comment out any repository-specific SigLevel settings because they override the global settings. This will result in no signature checking, which was the behavior before pacman 4. If you do this, you do not need to set up a keyring with pacman-key. You can change this option later if you decide to enable package verification.
Cannot import keys
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
There are multiple possible sources of this problem:
- An outdated archlinux-keyring package.
- Incorrect date.
- Your ISP blocked the port used to import PGP keys.
- Your pacman cache contains copies of unsigned packages from previous attempts.
- dirmngr is not correctly configured
- you have not upgraded in a long time and gpg/pacman does not handle that well
You might be stuck because of an outdated archlinux-keyring package when doing an upgrade synchronization.
Below are a few solutions that could work depending on your case.
Upgrade the system
See if upgrading the system can fix it first.
Change keyserver
If you suspect that something is not working right with the keyserver, you could try to switch to the Ubuntu keyserver. To do this, edit /etc/pacman.d/gnupg/gpg.conf and change the keyserver line to:
Clean cached packages
If you suspect that your pacman cache at /var/cache/pacman/pkg/ might contain unsigned packages, try cleaning the cache manually or run:
which removes all cached packages that have not been installed.
Signature is unknown trust
Sometimes when running pacman -Syu you might encounter this error:
This occurs because the packager ‘s key used in the package package-name is not present and/or not trusted in the local pacman-key gpg database. Pacman does not seem to always be able to check if the key was received and marked as trusted before continuing. This could also be because a key has expired since it was added to your keychain.
- Refreshing your keys with pacman-key —refresh-keys , or
- manually signing the untrusted key locally, or
- resetting all the keys, or
- setting temporarily SigLevel to TrustAll (not recommended).
Источник