Capítulo 2. Gestão de pacotes Debian

Índice

2.1. Pré-requisitos da gestão de pacotes Debian
2.1.1. Configuração de pacotes
2.1.2. Precauções básicas
2.1.3. A vida com actualizações eternas
2.1.4. Bases de arquivos Debian
2.1.5. Dependências de pacote
2.1.6. O fluxo de eventos da gestão de pacotes
2.1.7. Primeira resposta a problemas com a gestão do pacote
2.2. Operações básicas de gestão de pacotes
2.2.1. apt-get / apt-cache contra o aptitude
2.2.2. Operações básicas de gestão de pacotes com a linha de comandos
2.2.3. Uso interactivo do aptitude
2.2.4. Teclas de atalho do aptitude
2.2.5. Vistas de pacote sob o aptitude
2.2.6. Opções do método de pesquisa com o aptitude
2.2.7. A fórmula regex do aptitude
2.2.8. Resolução de dependências do aptitude
2.2.9. Logs de actividade de pacotes
2.3. Examples of aptitude operations
2.3.1. Listing packages with regex matching on package names
2.3.2. Browsing with the regex matching
2.3.3. Purgar pacotes removidos definitivamente
2.3.4. Tidying auto/manual install status
2.3.5. Actualização total ao sistema
2.4. Operações de gestão avançada de pacotes
2.4.1. Operações de gestão avançada de pacotes com linha de comandos
2.4.2. Verificação dos ficheiros pacotes instalados
2.4.3. Salvaguardar para problemas de pacotes.
2.4.4. Procurar nos meta dados do pacote
2.5. Os interiores da gestão de pacotes Debian
2.5.1. Meta dados do arquivo
2.5.2. Ficheiro "Release" de nível de topo e autenticidade:
2.5.3. Archive level "Release" files
2.5.4. Obter os meta dados do pacote
2.5.5. O estado do pacote para o APT
2.5.6. O estado do pacote para o aptitude
2.5.7. Copias locais dos pacotes obtidos
2.5.8. Nomes de ficheiros de pacotes Debian
2.5.9. O comando dpkg
2.5.10. O comando update-alternative
2.5.11. O comando dpkg-statoverride
2.5.12. O comando dpkg-divert
2.6. Recuperação de um sistema danificado
2.6.1. Incompatibilidade com configuração antiga de utilizador
2.6.2. Pacotes diferentes com ficheiros sobrepostos
2.6.3. Corrigir script de pacote danificado
2.6.4. Recuperação com o comando dpkg
2.6.5. Recuperar dados de selecção de pacotes
2.7. Dicas para a gestão de pacotes
2.7.1. Como escolher os pacotes Debian
2.7.2. Pacotes de fontes de arquivos misturados
2.7.3. Tweaking candidate version
2.7.4. Volatile and Backports
2.7.5. Descarga e actualização automática de pacotes
2.7.6. Limitar a largura de banda de descarga para o APT
2.7.7. Downgrade de emergência
2.7.8. Quem enviou o pacote?
2.7.9. O pacote equivs
2.7.10. Portando um pacote para o sistema stable
2.7.11. Servidor proxy para o APT
2.7.12. Pequeno arquivo de pacotes público
2.7.13. Gravar e copiar a configuração do sistema
2.7.14. Converter e instalar um pacote binário alienígena
2.7.15. Extrair um pacote sem o dpkg
2.7.16. Mais leituras para a gestão de pacotes
[Nota] Nota

Este capítulo é escrito assumindo o lançamento estável mais recente com o nome de código: squeeze.

Debian is a volunteer organization which builds consistent distributions of pre-compiled binary packages of free software and distributes them from its archive.

The Debian archive is offered by many remote mirror sites for access through HTTP and FTP methods. It is also available as CD-ROM/DVD.

The Debian package management system, when used properly, offers the user to install consistent sets of binary packages to the system from the archive. Currently, there are 30552 packages available for the amd64 architecture.

The Debian package management system has a rich history and many choices for the front end user program and back end archive access method to be used. Currently, we recommend the following.

Tabela 2.1. Lista de ferramentas de gestão de pacotes Debian

pacote popcon tamanho descrição
apt * V:90, I:99 5600 Advanced Packaging Tool (APT), front-end for dpkg providing "http", "ftp", and "file" archive access methods (apt-get/apt-cache commands included)
aptitude * V:25, I:98 11916 Gestor de pacotes baseado em terminal interactivo com aptitude(8)
update-manager-gnome * V:7, I:10 1221 Aplicação do GNOME que gere actualizações de software com o update-manager(8)
tasksel * V:5, I:93 904 ferramenta para seleccionar tarefas para instalação no sistema Debian (frontend para o APT)
unattended-upgrades * V:4, I:31 280 pacote de melhoramento para o APT para activar a instalação automática de actualizações de segurança
dselect * V:2, I:30 2404 gestor de pacotes baseado em terminal (o standard anterior, frontend para o APT e outros métodos de acesso antigos)
dpkg * V:92, I:99 6804 sistema de gestão de pacotes para Debian
synaptic * V:13, I:40 6464 gestor de pacotes gráfico (frontend do GNOME para o APT)
apt-utils * V:51, I:99 516 Programas utilitários do APT: apt-extracttemplates(1), apt-ftparchive(1), e apt-sortpkgs(1)
apt-listchanges * V:11, I:17 280 ferramenta de notificação do histórico de alterações do pacote
apt-listbugs * V:1.4, I:2 508 lista bugs críticos antes de cada instalação do APT
apt-file * V:2, I:9 188 Utilitário de busca de pacotes do APT - interface de linha de comandos
apt-rdepends * V:0.13, I:0.9 92 lista dependências de pacote recursivamente

2.1. Pré-requisitos da gestão de pacotes Debian

2.1.1. Configuração de pacotes

Aqui estão alguns pontos chave para configuração de pacotes no sistema Debian.

  • A configuração manual feita pelo administrador do sistema é respeitada. Por outras palavras, o sistema de configuração de pacotes não faz configurações intrusivas por conveniência.
  • Cada pacote vem com o seu próprio script de configuração com a interface de utilizador standard chamada debconf(7) para ajudar no processo inicial de instalação do pacote.
  • Os Programadores da Debian dão o seu melhor para tornar a sua experiência de actualização isenta de falhas com scripts de configuração de pacotes.
  • As funcionalidades totais do software empacotado estão disponíveis ao administrador do sistema. Mas aquelas com riscos de segurança estão desactivadas na instalação predefinida.
  • Se você activou manualmente um serviço com alguns riscos de segurança você é o responsável pelo confinamento de risco.
  • A configuração esotérica pode ser activada manualmente pelo administrador do sistema. Isto pode criar interferências com programas de ajuda genéricos populares para a configuração do sistema.

2.1.2. Precauções básicas

[Atenção] Atenção

Do not install packages from random mixture of suites. It probably breaks the package consistency which requires deep system management knowledge, such as compiler ABI, library version, interpreter features, etc.

The newbie Debian system administrator should stay with the stable release of Debian while applying only security updates. I mean that some of the following valid actions are better avoided, as a precaution, until you understand the Debian system very well. Here are some reminders.

  • Do not include testing or unstable in "/etc/apt/sources.list".
  • Não misture Debian standard com outros arquivos não Debian como o Ubuntu em "/etc/apt/sources.list".
  • Não crie o "/etc/apt/preferences".
  • Não altere o comportamento predefinido das ferramentas de gestão de pacotes através de ficheiros de configuração sem conhecer os seus impactos totais.
  • Não instale pacotes aleatórios por "dpkg -i <qualquer_pacote>".
  • Nunca instale pacotes aleatórios por "dpkg --force-all -i <qualquer_pacote>".
  • Não apague ou altere os ficheiros em "/var/lib/dpkg/".
  • Não sobrescreva ficheiros do sistema ao instalar programas de software directamente compilados da fonte.

    • Instale-os para "/usr/local" ou "/opt", se necessário.

Os efeitos não-compatíveis causados pelas acções em cima ao sistema de gestão de pacotes da Debian podem deixar o seu sistema inutilizado.

O administrador de sistema Debian sério que corre servidores de missões críticas, deve tomar precauções extra.

  • Não instale nenhuns pacotes incluindo as actualizações de segurança da Debian sem os testar completamente com as suas configurações particulares sob condições seguras.

    • Você como o administrador do sistema é o responsável final pelo seu sistema.
    • A longa história de estabilidade do sistema Debian não é uma garantia só por si.

2.1.3. A vida com actualizações eternas

Despite my warnings above, I know many readers of this document wish to run the testing or unstable suites of Debian as their main system for self-administered Desktop environments. This is because they work very well, are updated frequently, and offer the latest features.

[Cuidado] Cuidado

For your production server, the stable suite with the security updates is recommended. The same can be said for desktop PCs on which you can spend limited administration efforts, e.g. for your mother's PC.

It takes no more than simply setting the distribution string in the "/etc/apt/sources.list" to the suite name: "testing" or "unstable"; or the codename: "wheezy" or "sid". This makes you live the life of eternal upgrades.

The use of testing or unstable is a lot of fun but comes with some risks. Even though the unstable suite of Debian system looks very stable for most of the times, there have been some package problems on the testing and unstable suite of Debian system and a few of them were not so trivial to resolve. It may be quite painful for you. Sometimes, you may have a broken package or missing functionality for a few weeks.

Aqui estão algumas ideias para assegurar recuperação fácil e rápida de bugs nos pacotes Debian.

  • Make the system dual bootable by installing the stable suite of Debian system to another partition
  • Make the installation CD handy for the rescue boot
  • Considere instalar o apt-listbugs para verificar informação do Debian Bug Tracking System (BTS) antes da actualização.
  • Conheça o suficiente da infraestrutura do sistema de pacotes para contornar o problema
  • Crie um chroot ou ambiente semelhante para antecipadamente correr o sistema mais recente nele (veja Secção 9.8, “Sistema virtualizado”)

(If you can not do any one of these precautionary actions, you are probably not ready for the testing and unstable suites.)

Enlightenment with the following saves a person from the eternal karmic struggle of upgrade hell and let him reach Debian nirvana.

2.1.4. Bases de arquivos Debian

Vamos olhar para o arquivo Debian a partir da perspectiva do utilizador do sistema.

[Dica] Dica

Official policy of the Debian archive is defined at Debian Policy Manual, Chapter 2 - The Debian Archive.

For the typical HTTP access, the archive is specified in the "/etc/apt/sources.list" file as the following, e.g. for the current stable = squeeze system.

deb http://ftp.XX.debian.org/debian/ squeeze main contrib non-free
deb-src http://ftp.XX.debian.org/debian/ squeeze main contrib non-free

deb http://security.debian.org/ squeeze/updates main contrib
deb-src http://security.debian.org/ squeeze/updates main contrib

Please note "ftp.XX.debian.org" must be replaced with appropriate mirror site URL for your location, for USA "ftp.us.debian.org", which can be found in the list of Debian worldwide mirror sites. The status of these servers can be checked at Debian Mirror Checker site.

Here, I tend to use codename "squeeze" instead of suite name "stable" to avoid surprises when the next stable is released.

O significado de "/etc/apt/sources.list" é descrito em sources.list(5) e os pontos chave são os seguintes.

  • A linha "deb" define os pacotes binários.
  • A linha "deb-src" define os pacotes fonte.
  • O 1º argumento é o URL raiz do arquivo Debian.
  • O 2º argumento é o nome da distribuição: seja o nome de suite ou o nome de código.
  • O 3º argumento e seguintes são a lista de nomes de área de arquivo válidos do arquivo Debian.

The "deb-src" lines can safely be omitted (or commented out by placing "#" at the start of the line) if it is just for aptitude which does not access source related meta data. It speeds up the updates of the archive meta data. The URL can be "http://", "ftp://", "file://", ….

[Dica] Dica

If "sid" is used in the above example instead of "squeeze", the "deb: http://security.debian.org/" line for security updates in the "/etc/apt/sources.list" is not required. This is because there is no security update archive for "sid" (unstable).

Aqui está uma lista de URLs de sites de arquivo Debian e nomes das suites ou nomes de código usados no ficheiro de configuração.

Tabela 2.2. Lista de sites de arquivos Debian

URL do arquivo nome da suite (nome de código) objectivo
http://ftp.XX.debian.org/debian/ stable (squeeze) lançamento (squeeze) stable
http://ftp.XX.debian.org/debian/ testing (wheezy) lançamento (wheezy) testing
http://ftp.XX.debian.org/debian/ unstable (sid) lançamento (sid) unstable
http://ftp.XX.debian.org/debian/ experimental pré-lançamento experimental (opcional, apenas para programador)
http://ftp.XX.debian.org/debian/ stable-proposed-updates Actualizações para o próximo lançamento de ponto estável (opcional)
http://security.debian.org/ stable/updates actualizações de segurança para o lançamento stable (importante)
http://security.debian.org/ testing/updates actualizações de segurança para o lançamento testing (importante)
http://volatile.debian.org/debian-volatile/ volatile actualizações compatíveis para filtro de spam, clientes IM, etc.
http://volatile.debian.org/debian-volatile/ volatile-sloppy actualizações não-compatíveis para filtro de spam, clientes IM, etc.
http://backports.debian.org/debian-backports/ squeeze-backports newer backported packages for squeeze (official, optional)

[Cuidado] Cuidado

Only pure stable release with security updates provides the best stability. Running mostly stable release mixed with some packages from testing or unstable release is riskier than running pure unstable release for library version mismatch etc. If you really need the latest version of some programs under stable release, please use packages from the debian-volatile project and http://backports.debian.org (see Secção 2.7.4, “Volatile and Backports”) services. These services must be used with extra care.

[Cuidado] Cuidado

You should basically list only one of stable, testing, or unstable suites in the "deb" line. If you list any combination of stable, testing, and unstable suites in the "deb" line, APT programs slow down while only the latest archive is effective. Multiple listing makes sense for these when the "/etc/apt/preferences" file is used with clear objectives (see Secção 2.7.3, “Tweaking candidate version”).

[Dica] Dica

For the Debian system with the stable and testing suites, it is a good idea to include lines with "http://security.debian.org/" in the "/etc/apt/sources.list" to enable security updates as in the example above.

[Nota] Nota

The security bugs for the stable archive are fixed by the Debian security team. This activity has been quite rigorous and reliable. Those for the testing archive may be fixed by the Debian testing security team. For several reasons, this activity is not as rigorous as that for stable and you may need to wait for the migration of fixed unstable packages. Those for the unstable archive are fixed by the individual maintainer. Actively maintained unstable packages are usually in a fairly good shape by leveraging latest upstream security fixes. See Debian security FAQ for how Debian handles security bugs.

Tabela 2.3. Lista de área de arquivo Debian

área número de pacotes critério do componente do pacote
main 29887 complacente com DSFG e nenhuma dependência a non-free
contrib 202 complacente com DSFG mas com dependências a non-free
non-free 463 não complacente com DSFG

Here the number of packages in the above is for the amd64 architecture. Strictly speaking, only the main area archive shall be considered as the Debian system.

The Debian archive organization can be studied best by pointing your browser to the each archive URL appended with dists or pool.

The distribution is referred by two ways, the suite or codename. The word distribution is alternatively used as the synonym to the suite in many documentations. The relationship between the suite and the codename can be summarized as the following.

Tabela 2.4. A relação entre suite e nome de código

Temporização suite = stable suite = testing suite = unstable
após o lançamento squeeze nome de código = squeeze nome de código = wheezy nome de código = sid
após o lançamento wheezy nome de código = wheezy nome de código = wheezy+1 nome de código = sid

A história dos nomes de código está descrita em Debian FAQ: 6.3.1 Que outros nomes de código foram usados no passado?

In the stricter Debian archive terminology, the word "section" is specifically used for the categorization of packages by the application area. (Although, the word "main section" may sometimes be used to describe the Debian archive area named as "main".)

Every time a new upload is done by the Debian developer (DD) to the unstable archive (via incoming processing), DD is required to ensure uploaded packages to be compatible with the latest set of packages in the latest unstable archive.

If DD breaks this compatibility intentionally for important library upgrade etc, there is usually announcement to the debian-devel mailing list etc.

Before a set of packages are moved by the Debian archive maintenance script from the unstable archive to the testing archive, the archive maintenance script not only checks the maturity (about 10 days old) and the status of the RC bug reports for the packages but also tries to ensure them to be compatible with the latest set of packages in the testing archive. This process makes the testing archive very current and usable.

Through the gradual archive freeze process led by the release team, the testing archive is matured to make it completely consistent and bug free with some manual interventions. Then the new stable release is created by assigning the codename for the old testing archive to the new stable archive and creating the new codename for the new testing archive. The initial contents of the new testing archive is exactly the same as that of the newly released stable archive.

Both the unstable and the testing archives may suffer temporary glitches due to several factors.

  • Broken package upload to the archive (mostly for unstable)
  • Delay of accepting the new packages to the archive (mostly for unstable)
  • Archive synchronization timing issue (both for testing and unstable)
  • Intervenção manual no arquivo tal como remoção de pacotes (mais para testing) etc.

Se alguma vez você decidir usar estes arquivos, deverá ser capaz de corrigir ou contornar este tipo de problemas.

[Cuidado] Cuidado

For about few months after a new stable release, most desktop users should use the stable archive with its security updates even if they usually use unstable or testing archives. For this transition period, both unstable and testing archives are not good for most people. Your system is difficult to keep in good working condition with the unstable archive since it suffers surges of major upgrades for core packages. The testing archive is not useful either since it contains mostly the same content as the stable archive without its security support (Debian testing-security-announce 2008-12). After a month or so, the unstable archive may be usable if you are careful.

[Dica] Dica

When tracking the testing archive, problem caused by a removed package is usually worked around by installing corresponding package from the unstable archive which is uploaded for bug fix.

Veja Manual de Políticas Debian para definições de arquivo.

2.1.5. Dependências de pacote

O sistema Debian oferece um conjunto consistente de pacotes binários através do seu mecanismo de declaração de dependências binárias versionadas nos campos do ficheiro de controle. Aqui está uma definição deles um pouco simplificada.

  • "Depends"

    • Isto declara uma dependência absoluta e todos os pacotes listados neste campo têm de ser instalados ao mesmo tempo ou com antecedência.
  • "Pre-Depends"

    • Isto é como o Depends, excepto que requer a instalação completa de todos os pacotes listados com antecedência.
  • "Recommends"

    • Isto declara uma dependência forte mas não absoluta. A maioria dos utilizadores não iriam querer o pacote a menos que todos os pacotes listados neste campo estejam instalados.
  • "Suggests"

    • Isto declara uma dependência fraca. Muitos utilizadores deste pacote podem beneficiar ao instalar os pacotes listados neste campo mas podem ter as funções razoáveis sem eles.
  • "Enhances"

    • Isto declara uma dependência fraca como o Suggests mas funciona na direcção oposta.
  • "Breaks"

    • Isto declara uma incompatibilidade do pacote normalmente com alguma especificação de versão. Geralmente a resolução é actualizar todos os pacotes listados neste campo.
  • "Conflicts"

    • Isto declara uma incompatibilidade absoluta. Todos os pacotes listados neste campo têm de ser removidos para instalar este pacote.
  • "Replaces"

    • Isto é declarado quando os ficheiros instalados por este pacote substituem ficheiros nos pacotes listados.
  • "Provides"

    • Isto é declarado quando este pacote disponibiliza todos os ficheiros e funcionalidades dos pacotes listados.
[Nota] Nota

Por favor note que definir "Provides", "Conflicts" e "Replaces" em simultâneo a um pacote virtual é a configuração sã. Isto assegura que apenas um pacote real que disponibilize este pacote virtual possa ser instalado de cada vez.

A definição oficial incluindo dependências de fonte pode ser encontrada em O Manual de Políticas: Capítulo 7 - Declarar relações entre pacotes.

2.1.6. O fluxo de eventos da gestão de pacotes

Aqui está um resumo do fluxo de eventos simplificado da gestão de pacotes pelo APT.

  • Update ("aptitude update" ou "apt-get update"):

    1. Obtém meta-dados do arquivo a partir do arquivo remoto
    2. Reconstrói e actualiza os meta-dados locais para uso pelo APT
  • Upgrade ("aptitude safe-upgrade" e "aptitude full-upgrade", ou "apt-get upgrade" e "apt-get dist-upgrade"):

    1. Escolhe a versão candidata que geralmente é a versão mais recente disponível para todos os pacotes instalados (veja Secção 2.7.3, “Tweaking candidate version” para excepções).
    2. Resolve a dependência do pacote
    3. Obtém os pacotes binários seleccionados do arquivo remoto se a versão candidata é diferente da versão instalada.
    4. Desempacota os pacotes binários obtidos
    5. Correr o script preinst
    6. Instala os ficheiros binários
    7. Correr o script postinst
  • Install ("aptitude install …" ou "apt-get install …"):

    1. Escolhe os pacotes listados na linha de comandos
    2. Resolve a dependência do pacote
    3. Obtém os pacotes binários seleccionados a partir do arquivo remoto
    4. Desempacota os pacotes binários obtidos
    5. Correr o script preinst
    6. Instala os ficheiros binários
    7. Correr o script postinst
  • Remove ("aptitude remove …" ou "apt-get remove …"):

    1. Escolhe os pacotes listados na linha de comandos
    2. Resolve a dependência do pacote
    3. Correr o script prerm
    4. Remove os ficheiros instalados excepto os ficheiros de configuração
    5. Correr o script postrm
  • Purge ("aptitude purge …" ou "apt-get purge …"):

    1. Escolhe os pacotes listados na linha de comandos
    2. Resolve a dependência do pacote
    3. Correr o script prerm
    4. Remove os ficheiros instalados incluindo os ficheiros de configuração
    5. Correr o script postrm

Aqui, saltei intencionalmente detalhes técnicos para beneficiar a maioria.

2.1.7. Primeira resposta a problemas com a gestão do pacote

You should read the fine official documentation. The first document to read is the Debian specific "/usr/share/doc/<package_name>/README.Debian". Other documentation in "/usr/share/doc/<package_name>/" should be consulted too. If you set shell as Secção 1.4.2, “Personalizar o bash”, type the following.

$ cd <nome_do_pacote>
$ pager README.Debian
$ mc

Você pode precisar de instalar o pacote de documentação correspondente com o sufixo "-doc" no nome, para informações mais detalhadas.

Se você está a ter problemas com um pacote específico , certifique-se de verificar o Sistema de acompanhamento de bugs Debian (BTS) primeiro.

Tabela 2.5. Lista de sites web chave para resolver problemas com um pacote específico.

site web comando
Página inicial do Sistema de acompanhamento de bugs Debian (BTS) sensible-browser "http://bugs.debian.org/"
O relatório de bug de um nome de pacote conhecido sensible-browser "http://bugs.debian.org/<nome_do_pacote>"
O relatório de bug de um número de bug conhecido sensible-browser "http://bugs.debian.org/<número_do_bug>"

Procure no Google com palavras de busca incluindo "site:debian.org", "site:wiki.debian.org", "site:lists.debian.org", etc.

Quando você criar um relatório de bug, por favor use o comando reportbug(1).

2.2. Operações básicas de gestão de pacotes

As operações básicas de gestão de pacotes no sistema Debian podem ser executas por qualquer ferramenta de gestão de pacotes disponível no sistema Debian. Aqui vamos explicar as ferramentas de gestão básica de pacotes: apt-get / apt-cache e aptitude.

Para as operações de gestão de pacotes que envolvam a instalação ou actualização de metadados do pacote, você precisa de ter privilégios de root.

2.2.1. apt-get / apt-cache contra o aptitude

Os comandos apt-get e apt-cache são as ferramentas de gestão de pacotes mais básicas

  • O apt-get e o apt-cache oferecem apenas a interface de linha de comandos.
  • O apt-get é mais apropriado para a actualização maior ao sistema entre lançamentos, etc.
  • O apt-get oferece um resolvedor de pacotes robusto e estável que usa dados de estado dos pacotes comuns.
  • O apt-get foi actualizado para suportar a auto-instalação e auto-remoção de pacotes recomendados.
  • O apt-get foi actualizado para suportar o registo em log das actividades de pacotes.
  • O apt-cache oferece uma busca baseada em expressões regulares standard no nome do pacote e na descrição.
  • O apt-get e o apt-cache podem gerir múltiplas versões de pacotes usando o /etc/apt/preferences mas fica bastante pesado.

O comando aptitude é a ferramenta de gestão de pacotes mais versátil.

  • O aptitude oferece a interface de utilizador de texto interactiva de écran completo.
  • O aptitude também oferece uma interface de utilizador de linha de comandos.
  • O aptitude é mais apropriado para a gestão de pacotes interactiva diária como o inspeccionar os pacotes instalados e procurar pacotes disponíveis.
  • O aptitude oferece um resolvedor de pacotes avançado que também usa uns dados de estado de pacotes extra usados apenas pelo aptitude.
  • O aptitude suporta auto-instalação e auto-remoção de pacotes recomendados.
  • O aptitude suporta registo em log das actividades de pacotes.
  • O aptitude oferece um busca baseada em expressões regulares avançada em todos os metadados dos pacotes.
  • O aptitude pode gerir múltiplas versões de pacotes sem usar o /etc/apt/preferences e é bastante intuitivo.
[Nota] Nota

Although the aptitude command comes with rich features such as its enhanced package resolver, this complexity has caused (or may still causes) some regressions such as Bug #411123, Bug #514930, and Bug #570377. In case of doubt, please use the apt-get and apt-cache commands over the aptitude command.

2.2.2. Operações básicas de gestão de pacotes com a linha de comandos

Aqui estão algumas operações básicas de gestão de pacotes com a linha de comandos usando aptitude(8) e apt-get(8) / apt-cache(8).

Tabela 2.6. Operações básicas de gestão de pacotes com a linha de comandos usando aptitude(8) e apt-get(8) / apt-cache(8).

sintaxe do aptitude sintaxe do apt-get/apt-cache descrição
aptitude update apt-get update actualiza os metadados do arquivo de pacotes
aptitude install foo apt-get install foo instala a versão candidata do pacote "foo" com as suas dependências
aptitude safe-upgrade apt-get upgrade instala as versões candidatas dos pacotes instalados sem remover quaisquer outros pacotes
aptitude full-upgrade apt-get dist-upgrade <package> instala as versões candidatas dos pacotes instalados removendo outros pacotes caso necessário
aptitude remove foo apt-get remove foo remove o pacote "foo" deixando os seus ficheiros de configuração
N/D apt-get autoremove remove os pacote auto-instalados que já não são necessários
aptitude purge foo apt-get purge foo purga o pacote "foo" com os seus ficheiros de configuração
aptitude clean apt-get clean limpa completamente o repositório local de ficheiros de pacotes obtidos
aptitude autoclean apt-get autoclean clear out the local repository of retrieved package files for outdated packages
aptitude show foo apt-cache show <package> mostra informação detalhada acerca do pacote "foo"
aptitude search <regex> apt-cache search <regex> search packages which match <regex>
aptitude why <regex> N/D explain the reason why <regex> matching packages should be installed
aptitude why-not <regex> N/D explain the reason why <regex> matching packages can not be installed

[Nota] Nota

Since apt-get and aptitude share auto-installed package status (see Secção 2.5.5, “O estado do pacote para o APT”) after lenny, you can mix these tools without major troubles (see Bug #594490).

The difference between "safe-upgrade"/"upgrade" and "full-upgrade"/"dist-upgrade" only appears when new versions of packages stand in different dependency relationships from old versions of those packages. The "aptitude safe-upgrade" command does not install new packages nor remove installed packages.

The "aptitude why <regex>" can list more information by "aptitude -v why <regex>". Similar information can be obtained by "apt-cache rdepends <package>".

When aptitude command is started in the commandline mode and faces some issues such as package conflicts, you can switch to the full screen interactive mode by pressing "e"-key later at the prompt.

Você pode disponibilizar opções de comando logo após "aptitude".

Tabela 2.7. Opções de comando notáveis para o aptitude(8)

opção de comando descrição
-s simula o resultado do comando
-d faz apenas o download e não instala/actualiza
-D mostra breves explicações antes das instalações e remoções automáticas

Veja aptitude(8) e o "Manual de utilizador do aptitude" em "/usr/share/doc/aptitude/README" para mais.

[Dica] Dica

The dselect package is still available and was the preferred full screen interactive package management tool in previous releases.

2.2.3. Uso interactivo do aptitude

For the interactive package management, you start aptitude in interactive mode from the console shell prompt as follows.

$ sudo aptitude -u
Password:

This updates the local copy of the archive information and display the package list in the full screen with menu. Aptitude places its configuration at "~/.aptitude/config".

[Dica] Dica

If you want to use root's configuration instead of user's one, use "sudo -H aptitude …" instead of "sudo aptitude …" in the above expression.

[Dica] Dica

Aptitude automatically sets pending actions as it is started interactively. If you do not like it, you can reset it from menu: "Action" → "Cancel pending actions".

2.2.4. Teclas de atalho do aptitude

Notable key strokes to browse status of packages and to set "planned action" on them in this full screen mode are the following.

Tabela 2.8. Lista de teclas de atalho do aptitude

tecla tecla de atalho
F10 ou Ctrl-t menu
? display help for keystroke (more complete listing)
F10 → Ajuda → Manual do Utilizador mostra o Manual do Utilizador
u actualiza a informação de arquivo do pacote
+ mark the package for the upgrade or the install
- mark the package for the remove (keep configuration files)
_ mark the package for the purge (remove configuration files)
= place the package on hold
U mark all upgradable packages (function as full-upgrade)
g start downloading and installing selected packages
q sair do écran actual e guardar as alterações
x sair do écran actual e descartar as alterações
Enter ver informação acerca de um pacote
C ver o relatório de alterações de um pacote
l altera o limite dos pacotes mostrados
/ procura pela primeira correspondência
\ repetir a última pesquisa

The file name specification of the command line and the menu prompt after pressing "l" and "//" take the aptitude regex as described below. Aptitude regex can explicitly match a package name using a string started by "~n and followed by the package name.

[Dica] Dica

You need to press "U" to get all the installed packages upgraded to the candidate version in the visual interface. Otherwise only the selected packages and certain packages with versioned dependency to them are upgraded to the candidate version.

2.2.5. Vistas de pacote sob o aptitude

No modo de écran completo interactivo do aptitude(8), os pacotes na lista de pacotes são mostrados como no próximo exemplo.

idA   libsmbclient                             -2220kB 3.0.25a-1  3.0.25a-2

Aqui, esta linha significa desde a esquerda o seguinte.

  • A bandeira "estado actual" (a primeira letra)
  • A bandeira "acção planeada" (a segunda letra)
  • A bandeira "automático" ( a terceira letra)
  • O nome do Pacote
  • A alteração na utilização do espaço do disco atribuída a "acção planeada"
  • A versão actual do pacote
  • A versão candidata do pacote
[Dica] Dica

The full list of flags are given at the bottom of Help screen shown by pressing "?".

The candidate version is chosen according to the current local preferences (see apt_preferences(5) and Secção 2.7.3, “Tweaking candidate version”).

Several types of package views are available under the menu "Views".

Tabela 2.9. Lista de vistas para o aptitude

vista estado descrição da vista
Vista de Pacote Bom see Tabela 2.10, “A categorização das vista de pacotes standard” (default)
Auditoria de Recomendações Bom list packages which are recommended by some installed packages but not yet installed are listed
Lista de Pacotes Lisa Bom list packages without categorization (for use with regex)
Debtags Browser Muito utilizável list packages categorized according to their debtags entries
Categorical Browser Obsoleto list packages categorized according to their category (use Debtags Browser, instead)

The standard "Package View" categorizes packages somewhat like dselect with few extra features.

Tabela 2.10. A categorização das vista de pacotes standard

categoria descrição da vista
Pacotes Actualizáveis list packages organized as sectionareapackage
Pacotes Novos , ,
Pacotes Instalados , ,
Pacotes Não Instalados , ,
Pacotes Obsoletos ou Criados Localmente , ,
Pacotes Virtuais lista pacotes com a mesma função
Tarefas list packages with different functions generally needed for a task

[Dica] Dica

Tasks view can be used to cherry pick packages for your task.

2.2.6. Opções do método de pesquisa com o aptitude

Aptitude offers several options for you to search packages using its regex formula.

  • Linha de comandos da shell:

    • "aptitude search '<aptitude_regex>'" to list installation status, package name and short description of matching packages
    • "aptitude show '<package_name>'" to list detailed description of the package
  • modo de écran total interactivo:

    • "l" para limitar a vista de pacotes aos pacotes correspondentes
    • "/" for search to a matching package
    • "\" for backward search to a matching package
    • "n" for find-next
    • "N" for find-next (backward)
[Dica] Dica

The string for <package_name> is treated as the exact string match to the package name unless it is started explicitly with "~" to be the regex formula.

2.2.7. A fórmula regex do aptitude

The aptitude regex formula is mutt-like extended ERE (see Secção 1.6.2, “Expressões regulares”) and the meanings of the aptitude specific special match rule extensions are as follows.

Tabela 2.11. Lista da fórmula regex do aptitude

descrição da regra de correspondência extensa fórmula regex
corresponde com o nome do pacote ~n<regex_name>
corresponde com a descrição ~d<regex_description>
corresponde com nome da tarefa ~t<regex_task>
corresponde com debtag ~G<regex_debtag>
corresponde com o maintainer ~m<regex_maintainer>
corresponde com secção do pacote ~s<regex_section>
corresponde com versão do pacote ~V<regex_version>
corresponde com arquivo ~A{sarge,etch,sid}
corresponde com origem ~O{debian,…}
prioridade da correspondência ~p{extra,important,optional,required,standard}
corresponde com pacotes essenciais ~E
corresponde com pacotes virtuais ~v
corresponde com pacotes novos ~N
corresponde com acções pendentes ~a{install,upgrade,downgrade,remove,purge,hold,keep}
corresponde com os pacotes instalados ~i
match installed packages with A-mark (auto installed package) ~M
match installed packages without A-mark (administrator selected package) ~i!~M
corresponde com pacotes instalados e com actualizações disponíveis ~U
match removed but not purged packages ~c
match removed, purged or can-be-removed packages ~g
match packages with broken relation ~b
match packages with broken depends/predepends/conflict ~B<type>
match packages from which relation <type> is defined to <term> package ~D[<type>:]<term>
match packages from which broken relation <type> is defined to <term> package ~DB[<type>:]<term>
match packages to which the <term> package defines relation <type> ~R[<type>:]<term>
match packages to which the <term> package defines broken relation <type> ~RB[<type>:]<term>
match packages to which some other installed packages depend on ~R~i
match packages to which no other installed packages depend on !~R~i
match packages to which some other installed packages depend or recommend on ~R~i|~Rrecommends:~i
corresponde o pacote <term> com a versão filtrada ~S filter <term>
corresponde com todos os pacotes (true) ~T
não corresponde com nenhum pacote (false) ~F

  • The regex part is the same ERE as the one used in typical Unix-like text tools using "^", ".*", "$" etc. as in egrep(1), awk(1) and perl(1).
  • The relation <type> is one of (depends, predepends, recommends, suggests, conflicts, replaces, provides).
  • O tipo de relação predefinido é "depends".
[Dica] Dica

When <regex_pattern> is a null string, place "~T" immediately after the command.

Aqui estão alguns atalhos.

  • "~P<term>" == "~Dprovides:<term>"
  • "~C<term>" == "~Dconflicts:<term>"
  • "…~W term" == "(…|term)"

Users familiar with mutt pick up quickly, as mutt was the inspiration for the expression syntax. See "SEARCHING, LIMITING, AND EXPRESSIONS" in the "User's Manual" "/usr/share/doc/aptitude/README".

[Nota] Nota

With the lenny version of aptitude(8), the new long form syntax such as "?broken" may be used for regex matching in place for its old short form equivalent "~b". Now space character " " is considered as one of the regex terminating character in addition to tilde character "~". See "User's Manual" for the new long form syntax.

2.2.8. Resolução de dependências do aptitude

The selection of a package in aptitude not only pulls in packages which are defined in its "Depends:" list but also defined in the "Recommends:" list if the menu "F10 → Options → Dependency handling" is set accordingly. These auto installed packages are removed automatically if they are no longer needed under aptitude.

[Nota] Nota

Ante do lançamento do lenny, o apt-get e outras ferramentas standard do APT não ofereciam a funcionalidade autoremove.

2.2.9. Logs de actividade de pacotes

Você pode verificar o histórico de actividade de pacotes nos ficheiros log.

Tabela 2.12. Os ficheiros log para actividades de pacotes

ficheiro conteúdo
/var/log/dpkg.log Log da actividade de nível do dpkg para as actividades de todos os pacotes
/var/log/apt/term.log Log da actividade genérica do APT
/var/log/aptitude Log da actividade de comandos do aptitude

In reality, it is not so easy to get meaningful understanding quickly out from these logs. See Secção 9.2.10, “Gravar alterações em ficheiros de configuração” for easier way.

2.3. Examples of aptitude operations

Aqui estão alguns exemplos de operações do aptitude(8).

2.3.1. Listing packages with regex matching on package names

O seguinte comando lista pacotes com o regex a condizer com nomes de pacotes.

$ aptitude search '~n(pam|nss).*ldap'
p libnss-ldap - NSS module for using LDAP as a naming service
p libpam-ldap - Pluggable Authentication Module allowing LDAP interfaces

This is quite handy for you to find the exact name of a package.

2.3.2. Browsing with the regex matching

The regex "~dipv6" in the "New Flat Package List" view with "l" prompt, limits view to packages with the matching description and let you browse their information interactively.

2.3.3. Purgar pacotes removidos definitivamente

Você pode purgar todos os ficheiros de configuração restantes dos pacotes removidos.

Verifique os resultados do seguinte comando.

# aptitude search '~c'

If you think listed packages are OK to be purged, execute the following command.

# aptitude purge '~c'

You may want to do the similar in the interactive mode for fine grained control.

You provide the regex "~c" in the "New Flat Package List" view with "l" prompt. This limits the package view only to regex matched packages, i.e., "removed but not purged". All these regex matched packages can be shown by pressing "[" at top level headings.

Then you press "_" at top level headings such as "Installed Packages". Only regex matched packages under the heading are marked to be purged by this. You can exclude some packages to be purged by pressing "=" interactively for each of them.

This technique is quite handy and works for many other command keys.

2.3.4. Tidying auto/manual install status

Here is how I tidy auto/manual install status for packages (after using non-aptitude package installer etc.).

  1. Arranque o aptitude em modo interactivo como root.
  2. Type "u", "U", "f" and "g" to update and upgrade package list and packages.
  3. Type "l" to enter the package display limit as "~i(~R~i|~Rrecommends:~i)" and type "M" over "Installed Packages" as auto installed.
  4. Type "l" to enter the package display limit as "~prequired|~pimportant|~pstandard|~E" and type "m" over "Installed Packages" as manual installed.
  5. Type "l" to enter the package display limit as "~i!~M" and remove unused package by typing "-" over each of them after exposing them by typing "[" over "Installed Packages".
  6. Type "l" to enter the package display limit as "~i" and type "m" over "Tasks" as manual installed.
  7. Termina o aptitude.
  8. Start "apt-get -s autoremove|less" as root to check what are not used.
  9. Restart aptitude in interactive mode and mark needed packages as "m".
  10. Restart "apt-get -s autoremove|less" as root to recheck REMOVED contain only expected packages.
  11. Arranque "apt-get autoremove|less" como root para auto-remover os pacotes não usados.

A opção "m" sobre "Tasks" é uma opção para prevenir situações de remoção de pacotes em massa no futuro.

2.3.5. Actualização total ao sistema

[Nota] Nota

When moving to a new release etc, you should consider to perform a clean installation of new system even though Debian is upgradable as described below. This provides you a chance to remove garbages collected and exposes you to the best combination of latest packages. Of course, you should make a full backup of system to a safe place (see Secção 10.1.6, “Salvaguarda (backup) e recuperação”) before doing this. I recommend to make a dual boot configuration using different partition to have the smoothest transition.

You can perform system wide upgrade to a newer release by changing contents of the "/etc/apt/sources.list" file pointing to a new release and running the "apt-get update; apt-get dist-upgrade" command.

To upgrade from stable to testing or unstable, you replace "squeeze" in the "/etc/apt/sources.list" example of Secção 2.1.4, “Bases de arquivos Debian” with "wheezy" or "sid".

In reality, you may face some complications due to some package transition issues, mostly due to package dependencies. The larger the difference of the upgrade, the more likely you face larger troubles. For the transition from the old stable to the new stable after its release, you can read its new Release Notes and follow the exact procedure described in it to minimize troubles.

When you decide to move from stable to testing before its formal release, there are no Release Notes to help you. The difference between stable and testing could have grown quite large after the previous stable release and makes upgrade situation complicated.

You should make precautionary moves for the full upgrade while gathering latest information from mailing list and using common senses.

  1. Leia as "Notas de Lançamento" anteriores.
  2. Faça salvaguarda ao sistema completo (especialmente dados e informação de configuração).
  3. Tenha uma media de arranque à mão para o caso do gestor de arranque ficar danificado.
  4. Informe os utilizadores do sistema com bastante antecedência.
  5. Grave a actividade de actualização com o script(1).
  6. Apply "unmarkauto" to required packages, e.g., "aptitude unmarkauto vim", to prevent removal.
  7. Minimize installed packages to reduce chance of package conflicts, e.g., remove desktop task packages.
  8. Remova o ficheiro "/etc/apt/preferences" (desactiva o apt-pinning).
  9. Try to upgrade step wise: oldstablestabletestingunstable.
  10. Actualize o ficheiro "/etc/apt/sources.list" para apontar apenas para o novo arquivo e corra "aptitude update".
  11. Install, optionally, new core packages first, e.g., "aptitude install perl".
  12. Corra o comando "apt-get -s dist-upgrade" para aceder ao impacto.
  13. Corra o comando "apt-get dist-upgrade" em último lugar.
[Cuidado] Cuidado

It is not wise to skip major Debian release when upgrading between stable releases.

[Cuidado] Cuidado

In previous "Release Notes", GCC, Linux Kernel, initrd-tools, Glibc, Perl, APT tool chain, etc. have required some special attention for system wide upgrade.

For daily upgrade in unstable, see Secção 2.4.3, “Salvaguardar para problemas de pacotes.”.

2.4. Operações de gestão avançada de pacotes

2.4.1. Operações de gestão avançada de pacotes com linha de comandos

Here are list of other package management operations for which aptitude is too high-level or lacks required functionalities.

Tabela 2.13. Lista de operações de gestão avançada de pacotes

comando acção
COLUMNS=120 dpkg -l <padrão_do_nome_de_pacote> lista o estado de um pacote instalado para o relatório de bug
dpkg -L <nome_do_pacote> lista o conteúdo de um pacote instalado
dpkg -L <nome_do_pacote> | egrep '/usr/share/man/man.*/.+' lista os manuais para um pacote instalado
dpkg -S <padrão_do_nome_de_ficheiro> lista os pacotes instalados que condizem com o nome de ficheiro
apt-file search <padrão_do_nome_de_ficheiro> lista pacotes no arquivo que condizem com o nome de ficheiro
apt-file list <padrão_do_nome_de_pacote> lista os conteúdos dos pacotes no arquivo que condizem
dpkg-reconfigure <nome_do_pacote> reconfigura o pacote exacto
dpkg-reconfigure -p=low <nome_do_pacote> reconfigura o pacote exacto com as questões mais detalhadas
configure-debian reconfigura pacotes a partir do menu de écran completo
dpkg --audit faz auditoria ao sistema por pacotes parcialmente instalados
dpkg --configure -a configura todos os pacotes parcialmente instalados
apt-cache policy <nome_do_pacote_binário> mostra a versão disponível, a prioridade e informação de arquivo de um pacote binário
apt-cache madison <nome_do_pacote> mostra a versão disponível e informação de arquivo de um pacote
apt-cache showsrc <nome_do_pacote_binário> mostra informação do pacote fonte de um pacote binário
apt-get build-dep <nome_do_pacote> instala os pacote necessários para compilar pacote
apt-get source <nome_do_pacote> descarrega uma fonte (do arquivo standard)
dget <URL para ficheiro dsc> descarrega um pacote fonte (de outro arquivo)
dpkg-source -x <nome_do_pacote>_<versão>-<versão_debian>.dsc constrói uma árvore fonte a partir de um conjunto de pacotes fonte ("*.orig.tar.gz" e "*.debian.tar.gz"/"*.diff.gz")
debuild binary compila pacote(s) a partir de uma árvore fonte local
make-kpkg imagem_de_kernel compila um pacote de kernel a partir de uma árvore fonte de kernel
make-kpkg --initrd imagem_de_kernel compila um pacote de kernel a partir de uma árvore fonte de kernel com initramfs activa
dpkg -i <nome_de_pacote><versão>-<versão_debian><arquitectura>.deb instala um pacote local no sistema
debi <nome_de_pacote><versão>-<versão_debian><arquitectura>.dsc instala pacote(s) locais no sistema
dpkg --get-selection '*' >selecção.txt guarda a informação de estado de selecção a nível de pacotes do dpkg
dpkg --set-selection <selecção.txt define a informação de estado de selecção a nível de pacotes do dpkg
echo <package_name> hold | dpkg --set-selection set dpkg level package selection state for a package to hold (equivalent to "aptitude hold <package_name>")

[Cuidado] Cuidado

Lower level package tools such as "dpkg -i …" and "debi …" should be carefully used by the system administrator. It does not automatically take care required package dependencies. Dpkg's commandline options "--force-all" and similar (see dpkg(1)) are intended to be used by experts only. Using them without fully understanding their effects may break your whole system.

Por favor note o seguinte.

  • Toda a configuração do sistema e comandos de instalação requerem serem executados pelo root.
  • A contrário do aptitude que usa regex (veja Secção 1.6.2, “Expressões regulares”), os outros comandos de gestão de pacotes usam padrões como a shell glob (veja Secção 1.5.6, “Glob da shell”).
  • O apt-file(1) disponibilizado pelo pacote apt-file tem de correr "apt-file update" com antecedência.
  • O configure-debian(8) disponibilizado pelo pacote configure-debian corre o dpkg-reconfigure(8) como seu backend.
  • O dpkg-reconfigure(8) corre scripts de pacote usando o debconf(1) como o seu backend.
  • Os comandos "apt-get build-dep", "apt-get source" e "apt-cache showsrc" requerem entrada "deb-src" em "/etc/apt/sources.list".
  • Os dget(1), debuild(1), e debi(1) requerem o pacote devscripts.
  • Veja o procedimento de (re)empacotamento usando "apt-get source" em Secção 2.7.10, “Portando um pacote para o sistema stable”.
  • O comando make-kpkg requer o pacote kernel-package (veja Secção 9.7, “O kernel”).
  • Veja Secção 12.11, “Criando um pacote Debian” para empacotamento geral.

2.4.2. Verificação dos ficheiros pacotes instalados

A instalação de debsums permite a verificação dos ficheiros dos pacotes instalados contra valores MD5sum no ficheiro "/var/lib/dpkg/info/*.md5sums" com debsums(1). Veja Secção 10.4.5, “O sumário MD5” para saber como o MD5sum funciona.

[Nota] Nota

Porque a base de dados MD%sum pode ser adulterada por um intruso, o debsums(1) é de uso limitado como ferramenta de segurança. É bom apenas para verificar modificações locais pelo administrador ou danos devido a erros de media.

2.4.3. Salvaguardar para problemas de pacotes.

Muito utilizadores preferem seguir o lançamento unstable do sistema Debian pelas suas novas funcionalidades e pacotes. Isto torna o sistema para inclinado a ser atingido por bugs críticos dos pacotes.

A instalação do pacote apt-listbugs salvaguarda o seu sistema contra bugs críticos ao verificar automaticamente o Debian BTS por bugs críticos quando se actualiza com o sistema APT.

The installation of the apt-listchanges package provides important news in "NEWS.Debian" when upgrading with APT system.

2.4.4. Procurar nos meta dados do pacote

Although visiting Debian site http://packages.debian.org/ facilitates easy ways to search on the package meta data these days, let's look into more traditional ways.

The grep-dctrl(1), grep-status(1), and grep-available(1) commands can be used to search any file which has the general format of a Debian package control file.

The "dpkg -S <file_name_pattern>" can be used search package names which contain files with the matching name installed by dpkg. But this overlooks files created by the maintainer scripts.

If you need to make more elaborate search on the dpkg meta data, you need to run "grep -e regex_pattern *" command in the "/var/lib/dpkg/info/" directory. This makes you search words mentioned in package scripts and installation query texts.

If you wish to look up package dependency recursively, you should use apt-rdepends(8).

2.5. Os interiores da gestão de pacotes Debian

Vamos aprender como o sistema de gestão de pacotes Debian funciona internamente. Isto deverá ajudá-lo a criar a sua própria solução para alguns problemas com pacotes.

2.5.1. Meta dados do arquivo

Meta data files for each distribution are stored under "dist/<codename>" on each Debian mirror sites, e.g., "http://ftp.us.debian.org/debian/". Its archive structure can be browsed by the web browser. There are 6 types of key meta data.

Tabela 2.14. O conteúdo dos meta dados do arquivo Debian

ficheiro localização conteúdo
Release topo da distribuição descrição do arquivo e informação de integridade
Release.gpg topo da distribuição ficheiro de assinatura para o ficheiro "Release" assinado com a chave do arquivo
Contents-<architecture> topo da distribuição lista de todos os ficheiros para todos os pacotes no arquivo pertinente
Release topo de cada combinação de distribuição/área/arquitectura descrição do arquivo usada para a regra do apt_preferences(5)
Packages topo de cada combinação de distribuição/área/arquitectura-binário debian/control concatenado para pacotes binários
Sources topo de cada combinação de distribuição/área/fonte debian/control concatenado para pacotes fonte

In the recent archive, these meta data are stored as the compressed and differential files to reduce network traffic.

2.5.2. Ficheiro "Release" de nível de topo e autenticidade:

[Dica] Dica

The top level "Release" file is used for signing the archive under the secure APT system.

Each suite of the Debian archive has a top level "Release" file, e.g., "http://ftp.us.debian.org/debian/dists/unstable/Release", as follows.

Origin: Debian
Label: Debian
Suite: unstable
Codename: sid
Date: Sat, 26 Jan 2008 20:13:58 UTC
Architectures: alpha amd64 arm hppa hurd-i386 i386 ia64 m68k mips mipsel powerpc s390 sparc
Components: main contrib non-free
Description: Debian x.y Unstable - Not Released
MD5Sum:
 e9f11bc50b12af7927d6583de0a3bd06 22788722 main/binary-alpha/Packages
 43524d07f7fa21b10f472c426db66168  6561398 main/binary-alpha/Packages.gz
...
[Nota] Nota

Here, you can find my rationale to use the "suite", and "codeneme" in Secção 2.1.4, “Bases de arquivos Debian”. The "distribution" is used when referring to both "suite" and "codeneme". All archive "area" names offered by the archive are listed under "Component".

The integrity of the top level "Release" file is verified by cryptographic infrastructure called the secure apt.

  • The cryptographic signature file "Release.gpg" is created from the authentic top level "Release" file and the secret Debian archive key.
  • The public Debian archive key can be seeded into "/etc/apt/trusted.gpg";

  • The secure APT system verifies the integrity of the downloaded top level "Release" file cryptographically by this "Release.gpg" file and the public Debian archive key in "/etc/apt/trusted.gpg".

The integrity of all the "Packages" and "Sources" files are verified by using MD5sum values in its top level "Release" file. The integrity of all package files are verified by using MD5sum values in the "Packages" and "Sources" files. See debsums(1) and Secção 2.4.2, “Verificação dos ficheiros pacotes instalados”.

Since the cryptographic signature verification is very CPU intensive process than the MD5sum value calculation, use of MD5sum value for each package while using cryptographic signature for the top level "Release" file provides the good security with the performance (see Secção 10.4, “Infraestrutura da segurança de dados”).

2.5.3. Archive level "Release" files

[Dica] Dica

The archive level "Release" files are used for the rule of apt_preferences(5).

There are archive level "Release" files for all archive locations specified by "deb" line in "/etc/apt/sources.list", such as "http://ftp.us.debian.org/debian/dists/unstable/main/binary-amd64/Release" or "http://ftp.us.debian.org/debian/dists/sid/main/binary-amd64/Release" as follows.

Archive: unstable
Component: main
Origin: Debian
Label: Debian
Architecture: amd64
[Cuidado] Cuidado

For "Archive:" stanza, suite names ("stable", "testing", "unstable", …) are used in the Debian archive while codenames ("dapper", "feisty", "gutsy", "hardy", "intrepid", …) are used in the Ubuntu archive.

For some archives, such as experimental, volatile-sloppy, and squeeze-backports, which contain packages which should not be installed automatically, there is an extra line, e.g., "http://ftp.us.debian.org/debian/dists/experimental/main/binary-amd64/Release" as follows.

Archive: experimental
Component: main
Origin: Debian
Label: Debian
NotAutomatic: yes
Architecture: amd64

Please note that for normal archives without "NotAutomatic: yes", the default Pin-Priority value is 500, while for special archives with "NotAutomatic: yes", the default Pin-Priority value is 1 (see apt_preferences(5) and Secção 2.7.3, “Tweaking candidate version”).

2.5.4. Obter os meta dados do pacote

When APT tools, such as aptitude, apt-get, synaptic, apt-file, auto-apt…, are used, we need to update the local copies of the meta data containing the Debian archive information. These local copies have following file names corresponding to the specified distribution, area, and architecture names in the "/etc/apt/sources.list" (see Secção 2.1.4, “Bases de arquivos Debian”).

  • "/var/lib/apt/lists/ftp.us.debian.org_debian_dists_<distribuição>_Release"
  • "/var/lib/apt/lists/ftp.us.debian.org_debian_dists_<distribuição>_Release.gpg"
  • "/var/lib/apt/lists/ftp.us.debian.org_debian_dists_<distribution>_<area>_binary-<architecture>_Packages"
  • "/var/lib/apt/lists/ftp.us.debian.org_debian_dists_<distribution>_<area>_source_Sources"
  • "/var/cache/apt/apt-file/ftp.us.debian.org_debian_dists_<distribution>_Contents-<architecture>.gz" (for apt-file)

First 4 types of files are shared by all the pertinent APT commands and updated from command line by "apt-get update" and "aptitude update". The "Packages" meta data are updated if there is the "deb" line in "/etc/apt/sources.list". The "Sources" meta data are updated if there is the "deb-src" line in "/etc/apt/sources.list".

The "Packages" and "Sources" meta data contain "Filename:" stanza pointing to the file location of the binary and source packages. Currently, these packages are located under the "pool/" directory tree for the improved transition over the releases.

Local copies of "Packages" meta data can be interactively searched with the help of aptitude. The specialized search command grep-dctrl(1) can search local copies of "Packages" and "Sources" meta data.

Local copy of "Contents-<architecture>" meta data can be updated by "apt-file update" and its location is different from other 4 ones. See apt-file(1). (The auto-apt uses different location for local copy of "Contents-<architecture>.gz" as default.)

2.5.5. O estado do pacote para o APT

In addition to the remotely fetched meta data, the APT tool after lenny stores its locally generated installation state information in the "/var/lib/apt/extended_states" which is used by all APT tools to track all auto installed packages.

2.5.6. O estado do pacote para o aptitude

In addition to the remotely fetched meta data, the aptitude command stores its locally generated installation state information in the "/var/lib/aptitude/pkgstates" which is used only by it.

2.5.7. Copias locais dos pacotes obtidos

Todos os pacotes obtidos remotamente via mecanismo APT são armazenados em "/var/cache/apt/packages" até que sejam limpos.

2.5.8. Nomes de ficheiros de pacotes Debian

Ficheiros de pacotes Debian têm estruturas de nomes particulares.

Tabela 2.15. A estrutura de nomes dos pacotes Debian

tipo de pacote estrutura de nomes
O pacote binário (a.k.a deb) <nome_de_pacote>_<epoch>:<versão_upstream>-<versão.debian>-<arquitectura>.deb
O pacote binário (a.k.a udeb) <nome_de_pacote>_<epoch>:<versão_upstream>-<versão.debian>-<arquitectura>.udeb
O pacote fonte (fonte da origem) <nome_de_pacote>_<epoch>:<versão_upstream>-<versão.debian>.orig.tar.gz
O pacote fonte 1.0 (alterações da Debian) <nome_de_pacote>_<epoch>:<versão_upstream>-<versão.debian>.diff.gz
O pacote fonte 3.0 (quilt) (alterações da Debian) <nome_de_pacote>_<epoch>:<versão_upstream>-<versão.debian>.debian.tar.gz
O pacote fonte (descrição) <nome_do_pacote>_<epoch>:<versão_upstream>-<versão.debian>.dsc

[Dica] Dica

Aqui apenas são descritos formatos de pacote fonte básicos. Veja mais em dpkg-source(1).

Tabela 2.16. Os caracteres utilizáveis para cada componente nos nomes de pacotes Debian

componente do nome caracteres utilizáveis (regex) existência
<nome-do-pacote> [a-z,A-Z,0-9,.,,-] necessário
<epoch>: [0-9]+: opcional
<versão-upstream> [a-z,A-Z,0-9,.,,-,:] necessário
<versão.debian> [a-z,A-Z,0-9,.,,~] opcional

[Nota] Nota

Você pode verificar a ordem de versão de pacotes pelo dpkg(1), ex., "dpkg --compare-versions 7.0 gt 7.~pre1 ; echo $?" .

[Nota] Nota

The debian-installer (d-i) uses udeb as the file extension for its binary package instead of normal deb. An udeb package is a stripped down deb package which removes few non-essential contents such as documentation to save space while relaxing the package policy requirements. Both deb and udeb packages share the same package structure. The "u" stands for micro.

2.5.9. O comando dpkg

dpkg(1) é a ferramenta de nível mais baixo para a gestão de pacotes Debian. É muito poderosa e tem que ser usada com cuidado.

Enquanto instala o pacote chamado "<nome_de_pacote>", o dpkg processa-o na seguinte ordem.

  1. Desempacotar o ficheiro deb ("ar -x" equivalente)
  2. Executa "<nome_de_pacote>.preinst" usando o debconf(1)
  3. Instala o conteúdo do pacote no sistema (equivalente a "tar -x")
  4. Execute "<nome_de_pacote>.postinst" usando o debconf(1)

O sistema debconf disponibiliza interacção standard com o utilizador com suporte a I18N e L10N (Capítulo 8, I18N e L10N).

Tabela 2.17. Os ficheiros notáveis criados pelo dpkg

ficheiro descrição dos conteúdos
/var/lib/dpkg/info/<nome_do_pacote>.conffiles lista de ficheiros de configuração. (modificável pelo utilizador)
/var/lib/dpkg/info/<nome_do_pacote>.list lista de ficheiros e directórios instalados pelo pacote
/var/lib/dpkg/info/<nome_do_pacote>.md5sums lista de valores de hash MD5 para os ficheiros instalados pelo pacote
/var/lib/dpkg/info/<nome_do_pacote>.preinst script de pacote executado antes da instalação do pacote
/var/lib/dpkg/info/<nome_do_pacote>.postinst script de pacote executado após a instalação do pacote
/var/lib/dpkg/info/<nome_do_pacote>.prerm script de pacote executado antes da remoção do pacote
/var/lib/dpkg/info/<nome_do_pacote>.postrm script de pacote executado após a remoção do pacote
/var/lib/dpkg/info/<nome_do_pacote>.config script de pacote para o sistema debconf
/var/lib/dpkg/alternatives/<nome_do_pacote> a informação alternativa usada pelo comando update-alternatives
/var/lib/dpkg/available a informação de disponibilidade para todos os pacotes
/var/lib/dpkg/diversions a informação de diversões usada pelo dpkg(1) e definida pelo `dpkg-divert`(8)
/var/lib/dpkg/statoverride a informação de estado de sobreposição usada pelo dpkg(1) e definida pelo `dpkg-statoverride`(8)
/var/lib/dpkg/status a informação de estado para todos os pacotes
/var/lib/dpkg/status-old o backup de primeira geração do ficheiro "var/lib/dpkg/status"
/var/backups/dpkg.status* o backup de segunda geração e os mais antigos do ficheiro "var/lib/dpkg/status"

O ficheiro "status" também é usado por ferramentas como o dpkg(1), o "dselect update" e o "apt-get -u dselect-upgrade".

O comando especializado de busca grep-dctrl(1) pode procurar as cópias locais dos meta dados "status" e "available"

[Dica] Dica

In the debian-installer environment, the udpkg command is used to open udeb packages. The udpkg command is a stripped down version of the dpkg command.

2.5.10. O comando update-alternative

The Debian system has mechanism to install somewhat overlapping programs peacefully using update-alternatives(8). For example, you can make the vi command select to run vim while installing both vim and nvi packages.

$ ls -l $(type -p vi)
lrwxrwxrwx 1 root root 20 2007-03-24 19:05 /usr/bin/vi -> /etc/alternatives/vi
$ sudo update-alternatives --display vi
...
$ sudo update-alternatives --config vi
  Selection    Command
 ----------------------------------------------
      1        /usr/bin/vim
*+    2        /usr/bin/nvi

Enter para manter a predefinição[*], ou escreva o número da selecção: 1

O sistema de alternativas da Debian mantêm a sua selecção como links simbólicos em "/etc/alternatives/". O processo de selecção usa um ficheiro correspondente em "/var/lib/dpkg/alternatives/".

2.5.11. O comando dpkg-statoverride

Stat overrides provided by the dpkg-statoverride(8) command are a way to tell dpkg(1) to use a different owner or mode for a file when a package is installed. If "--update" is specified and file exists, it is immediately set to the new owner and mode.

[Cuidado] Cuidado

The direct alteration of owner or mode for a file owned by the package using chmod or chown commands by the system administrator is reset by the next upgrade of the package.

[Nota] Nota

I use the word file here, but in reality this can be any filesystem object that dpkg handles, including directories, devices, etc.

2.5.12. O comando dpkg-divert

File diversions provided by the dpkg-divert(8) command are a way of forcing dpkg(1) not to install a file into its default location, but to a diverted location. The use of dpkg-divert is meant for the package maintenance scripts. Its casual use by the system administrator is deprecated.

2.6. Recuperação de um sistema danificado

Quando corre o sistema unstable, espera-se que o administrador saiba recuperar o sistema de situações de gestão quebrada de pacotes.

[Cuidado] Cuidado

Alguns métodos descritos aqui são acções de alto risco. Você foi avisado!

2.6.1. Incompatibilidade com configuração antiga de utilizador

If a desktop GUI program experienced instability after significant upstream version upgrade, you should suspect interferences with old local configuration files created by it. If it is stable under newly created user account, this hypothesis is confirmed. (This is a bug of packaging and usually avoided by the packager.)

To recover stability, you should move corresponding local configuration files and restart the GUI program. You may need to read old configuration file contents to recover configuration information later. (Do not erase them too quickly.)

2.6.2. Pacotes diferentes com ficheiros sobrepostos

Archive level package management systems, such as aptitude(8) or apt-get(1), do not even try to install packages with overlapped files using package dependencies (see Secção 2.1.5, “Dependências de pacote”).

Errors by the package maintainer or deployment of inconsistently mixed source of archives (see Secção 2.7.2, “Pacotes de fontes de arquivos misturados”) by the system administrator may create situation with incorrectly defined package dependencies. When you install a package with overlapped files using aptitude(8) or apt-get(1) under such situation, dpkg(1) which unpacks package ensures to return error to the calling program without overwriting existing files.

[Cuidado] Cuidado

The use of third party packages introduces significant system risks via maintainer scripts which are run with root privilege and can do anything to your system. The dpkg(1) command only protects against overwriting by the unpacking.

Você pode contornar tal problema de instalação ao remover primeiro o pacote antigo , <pacote_antigo>, e ofensivo.

$ sudo dpkg -P <pacote-antigo>

2.6.3. Corrigir script de pacote danificado

When a command in the package script returns error for some reason and the script exits with error, the package management system aborts their action and ends up with partially installed packages. When a package contains bugs in its removal scripts, the package may become impossible to remove and quite nasty.

Para o problema do script de pacote de "<nome_do_pacote>", você deve observar os seguintes scripts do pacote.

  • "/var/lib/dpkg/info/<nome_do_pacote>.preinst"
  • "/var/lib/dpkg/info/<nome_do_pacote>.postinst"
  • "/var/lib/dpkg/info/<nome_do_pacote>.prerm"
  • "/var/lib/dpkg/info/<nome_do_pacote>.postrm"

Editar o script do pacote ofensivo a partir de root usando as seguintes técnicas.

  • desactivar a linha ofensiva ao preceder um "#"
  • força um retorno com sucesso ao acrescentar a linha ofensiva com "|| true"

Configurar todos os pacotes parcialmente instalados com o seguinte comando.

# dpkg --configure -a

2.6.4. Recuperação com o comando dpkg

Como o dpkg é uma ferramenta de pacotes de muito baixo nível, pode funcionar sob situações muito más como um sistema que não arranca sem ligação a rede. Vamos assumir que o pacote foo está danificado e precisa de ser substituído.

Você pode ainda encontrar cópias em cache de uma versão antiga livre de bugs do pacote foo no directório de cache de pacotes: "/var/cache/apt/archives/". (se não, você pode descarregá-lo a partir do arquivo http://snapshot.debian.net/ ou copiá-lo da cache de pacotes de uma máquina funcional.)

Se puder arrancar o sistema, você pode instalá-lo com o seguinte comando.

# dpkg -i /caminho/para/foo_<versão_antiga>_<arquitectura>.deb
[Dica] Dica

Se os danos no sistema forem menores, você pode alternativamente fazer downgrade (regredir a versão) ao sistema completo como Secção 2.7.7, “Downgrade de emergência” usando o sistema APt de alto nível.

Se o seu sistema não puder arrancar pelo disco rijo, você precisa procurar outras maneiras de arrancá-lo.

  1. Arranque o sistema usando o CD de instalação de Debian (debian-installer) em modo de recuperação.
  2. Monte o sistema danificado no disco rijo em "/target
  3. Instale uma versão antiga do pacote foo com o seguinte.
# dpkg --root /destino -i /caminho/para/foo_<versão_antiga>_<arquitectura>.deb

Este exemplo funciona mesmo se o comando dpkg no disco rijo estiver danificado.

[Dica] Dica

Any GNU/Linux system started by another system on hard disk, live GNU/Linux CD, bootable USB-key drive, or netboot can be used similarly to rescue broken system.

If attempting to install a package this way fails due to some dependency violations and you really need to do this as the last resort, you can override dependency using dpkg's "--ignore-depends", "--force-depends" and other options. If you do this, you need to make serious effort to restore proper dependency later. See dpkg(8) for details.

[Nota] Nota

When your system is seriously broken, you should make a full backup of system to a safe place (see Secção 10.1.6, “Salvaguarda (backup) e recuperação”) and should perform a clean installation. This is less time consuming and produces better results in the end.

2.6.5. Recuperar dados de selecção de pacotes

If "/var/lib/dpkg/status" becomes corrupt for any reason, the Debian system loses package selection data and suffers severely. Look for the old "/var/lib/dpkg/status" file at "/var/lib/dpkg/status-old" or "/var/backups/dpkg.status.*".

Manter "/var/backups/" numa partição separada pode ser uma boa ideia porque este directório contém muitos dados importantes do sistema .

For serious breakage, I recommend to make fresh re-install after making backup of the system. Even if everything in "/var/" is gone, you can still recover some information from directories in "/usr/share/doc/" to guide your new installation.

Reinstalar o sistema mínimo (ambiente de trabalho).

# mkdir -p /caminho/para/sistema/antigo

Monte o sistema antigo em "/caminho/para/sistema/antigo/".

# cd /caminho/para/sistema/antigo/usr/share/doc
# ls -1 >~/ls1.txt
# cd /usr/share/doc
# ls -1 >>~/ls1.txt
# cd
# sort ls1.txt | uniq | less

Então são-lhe apresentados nomes de pacotes para instalar. (Podem existir alguns nomes não de pacotes como "texmf".)

2.7. Dicas para a gestão de pacotes

2.7.1. Como escolher os pacotes Debian

Você pode procurar os pacotes que satisfaçam as suas necessidades com o aptitude a partir da descrição do pacote ou a partir da lista "Tarefas".

When you encounter more than 2 similar packages and wonder which one to install without "trial and error" efforts, you should use some common sense. I consider following points are good indications of preferred packages.

  • Essencial: yes > no
  • Componente: main > contrib > non-free
  • Prioridade: required > important > standard > optional > extra
  • Tasks: pacotes listados em tarefas como "Ambiente de Trabalho"
  • Pacotes seleccionados pela dependência de pacote (ex., python2.4 por python)
  • Popcon: higher in the vote and install number
  • Changelog: actualizações regulares feitas pelo responsável do pacote
  • BTS: No RC bugs (no critical, no grave, and no serious bugs)
  • BTS: responsive maintainer to bug reports
  • BTS: higher number of the recently fixed bugs
  • BTS: lower number of remaining non-wishlist bugs

Debian being a volunteer project with distributed development model, its archive contains many packages with different focus and quality. You must make your own decision what to do with them.

2.7.2. Pacotes de fontes de arquivos misturados

[Cuidado] Cuidado

Installing packages from mixed source of archives is not supported by the official Debian distribution except for officially supported particular combinations of archives such as stable with security updates and volatile updates.

Here is an example of operations to include specific newer upstream version packages found in unstable while tracking testing for single occasion.

  1. Altere o ficheiro "/etc/apt/sources.list" temporariamente para entrada única "unstable".
  2. Correr "aptitude update".
  3. Correr "aptitude install <nome-do-pacote>".
  4. Recupere o ficheiro "/etc/apt/sources.list" original para testing.
  5. Correr "aptitude update".

You do not create the "/etc/apt/preferences" file nor need to worry about apt-pinning with this manual approach. But this is very cumbersome.

[Cuidado] Cuidado

When using mixed source of archives, you must ensure compatibility of packages by yourself since the Debian does not guarantee it. If package incompatibility exists, you may break system. You must be able to judge these technical requirements. The use of mixed source of random archives is completely optional operation and its use is not something I encourage you to use.

As regras gerais para instalar pacotes de arquivos diferentes são as seguintes.

  • Nenhum pacote binário de ("Arquitectura: todos") é mais seguro para instalar.

    • pacotes de documentação: nenhum requisito especial
    • pacotes de programa interpretador: interpretador compatível tem de estar disponível
  • Binary packages (non "Architecture: all") usually face many road blocks and unsafe to install.

    • compatibilidade de versão de biblioteca (incluindo a "libc")
    • related utility program version compatibility
    • compatibilidade da ABI do Kernel
    • Compatibilidade C++ ABI
[Nota] Nota

In order to make a package to be safer to install, some commercial non-free binary program packages may be provided with completely statically linked libraries. You should still check ABI compatibility issues etc. for them.

[Nota] Nota

Except to avoid broken package for a short term, installing binary packages from officially unsupported archives is generally bad idea. This is true even if you use apt-pinning (see Secção 2.7.3, “Tweaking candidate version”). You should consider chroot or similar techniques (see Secção 9.8, “Sistema virtualizado”) to run programs from different archives.

2.7.3. Tweaking candidate version

Without the "/etc/apt/preferences" file, APT system choses the latest available version as the candidate version using the version string. This is the normal state and most recommended usage of APT system. All officially supported combinations of archives do not require the "/etc/apt/preferences" file since some archives which should not be used as the automatic source of upgrades are marked as NotAutomatic and dealt properly.

[Dica] Dica

The version string comparison rule can be verified with, e.g., "dpkg --compare-versions ver1.1 gt ver1.1~1; echo $?" (see dpkg(1)).

When you install packages from mixed source of archives (see Secção 2.7.2, “Pacotes de fontes de arquivos misturados”) regularly, you can automate these complicated operations by creating the "/etc/apt/preferences" file with proper entries and tweaking the package selection rule for candidate version as described in apt_preferences(5). This is called apt-pinning.

[Atenção] Atenção

Use of apt-pinning by a novice user is sure call for major troubles. You must avoid using apt-pinning except when you absolutely need it.

[Cuidado] Cuidado

When using apt-pinning, you must ensure compatibility of packages by yourself since the Debian does not guarantee it. The apt-pinning is completely optional operation and its use is not something I encourage you to use.

[Cuidado] Cuidado

Archive level Release files (see Secção 2.5.3, “Archive level "Release" files”) are used for the rule of apt_preferences(5). Thus apt-pinning works only with "suite" name for normal Debian archives and security Debian archives. (This is different from Ubuntu archives). For example, you can do "Pin: release a=unstable" but can not do "Pin: release a=sid" in the "/etc/apt/preferences" file.

[Cuidado] Cuidado

When you use non-Debian archive as a part of apt-pinning, you should check what they are intended for and also check their credibility. For example, Ubuntu and Debian are not meant to be mixed.

[Nota] Nota

Even if you do not create the "/etc/apt/preferences" file, you can do fairly complex system operations (see Secção 2.6.4, “Recuperação com o comando dpkg” and Secção 2.7.2, “Pacotes de fontes de arquivos misturados”) without apt-pinning.

Here is a simplified explanation of apt-pinning technique.

APT system choses highest Pin-Priority upgrading package from available package sources defined in the "/etc/apt/sources.list" file as the candidate version package. If the Pin-Priority of the package is larger than 1000, this version restriction for upgrading is dropped to enable downgrading (see Secção 2.7.7, “Downgrade de emergência”).

Pin-Priority value of each package is defined by "Pin-Priority" entries in the "/etc/apt/preferences" file or uses its default value.

Tabela 2.18. List of the default Pin-Priority value for each package source type

Prioridade de Pin predefinida tipo de fonte de pacote
990 arquivo de lançamento de destino
500 arquivo normal
100 pacote instalado
1 arquivo Não Automático

The target release archive can be set by several methods.

  • "/etc/apt/apt.conf" configuration file with "APT::Default-Release "stable";" line
  • command line option, e.g., "apt-get install -t testing some-package"

The NotAutomatic archive is set by archive server having its archive level Release file (see Secção 2.5.3, “Archive level "Release" files”) containing "NotAutomatic: yes".

The apt-pinning situation of <package> from multiple archive sources is displayed by "apt-cache policy <package>".

  • A line started with "Package pin:" lists the package version of pin if association just with <package> is defined, e.g., "Package pin: 0.190".
  • No line with "Package pin:" exists if no association just with <package> is defined.
  • The Pin-Priority value associated just with <package> is listed right side of all version strings, e.g., "0.181 700".
  • "0" is listed right side of all version strings if no association just with <package> is defined, e.g., "0.181 0".
  • The Pin-Priority values of archives (defined as "Package: *" in the "/etc/apt/preferences" file) are listed left side of all archive paths, e.g., "200 http://backports.debian.org/debian-backports/ squeeze-backports/main Packages".

Here is an example of apt-pinning technique to include specific newer upstream version packages found in unstable regularly upgraded while tracking testing. You list all required archives in the "/etc/apt/sources.list" file as the following.

deb http://ftp.us.debian.org/debian/ testing main contrib non-free
deb http://ftp.us.debian.org/debian/ unstable main contrib non-free
deb http://security.debian.org/ testing/updates main contrib

Configure o ficheiro "/etc/apt/preferences" como o seguinte.

Package: *
Pin: release a=testing
Pin-Priority: 500

Package: *
Pin: release a=unstable
Pin-Priority: 200

When you wish to install a package named "<package-name>" with its dependencies from unstable archive under this configuration, you issue the following command which switches target release with "-t" option (Pin-Priority of unstable becomes 990.).

$ sudo apt-get install -t unstable <nome-do-pacote>

With this configuration, usual execution of "apt-get upgrade" and "apt-get dist-upgrade" (or "aptitude safe-upgrade" and "aptitude full-upgrade") upgrades packages which were installed from testing archive using current testing archive and packages which were installed from unstable archive using current unstable archive.

[Cuidado] Cuidado

Tenha cuidado para não remover a entrada "testing" do ficheiro "/etc/apt/sources.list". Sem a entrada "testing lá, o sistema APT actualiza pacotes usando o arquivo unstable mais recente.

[Dica] Dica

I usually edit the "/etc/apt/sources.list" file to comment out "unstable" archive entry right after above operation. This avoids slow update process of having too many entries in the "/etc/apt/sources.list" file although this prevents upgrading packages which were installed from unstable archive using current unstable archive.

[Dica] Dica

If "Pin-Priority: 20" is used instead of "Pin-Priority: 200" for the "/etc/apt/preferences" file, already installed packages having Pin-Priority value of 100 are not upgraded by unstable archive even if "testing" entry in the "/etc/apt/sources.list" file is removed.

If you wish to track particular packages in unstable automatically without initial "-t unstable" installation, you must create the "/etc/apt/preferences" file and explicitly list all those packages at the top of it as the following.

Package: <package-1>
Pin: release a=unstable
Pin-Priority: 700

Package: <package-2>
Pin: release a=unstable
Pin-Priority: 700

These set Pin-Priority value for each specific package. For example, in order to track the latest unstable version of this "Debian Reference" in English, you should have following entries in the "/etc/apt/preferences" file.

Package: debian-reference-en
Pin: release a=unstable
Pin-Priority: 700

Package: debian-reference-common
Pin: release a=unstable
Pin-Priority: 700
[Dica] Dica

This apt-pinning technique is valid even when you are tracking stable archive. Documentation packages have been always safe to install from unstable archive in my experience, so far.

Here is another example of apt-pinning technique to include specific newer upstream version packages found in experimental while tracking unstable. You list all required archives in the "/etc/apt/sources.list" file as the following.

deb http://ftp.us.debian.org/debian/ unstable main contrib non-free
deb http://ftp.us.debian.org/debian/ experimental main contrib non-free
deb http://security.debian.org/ testing/updates main contrib

The default Pin-Priority value for experimental archive is always 1 (<<100) since it is NotAutomatic archive (see Secção 2.5.3, “Archive level "Release" files”). There is no need to set Pin-Priority value explicitly in the "/etc/apt/preferences" file just to use experimental archive unless you wish to track particular packages in it automatically for next upgrading.

2.7.4. Volatile and Backports

There are debian-volatile project and backports.debian.org archives which provide updgrade packages for stable.

[Atenção] Atenção

Do not use all packages available in the NotAutomatic archives such as squeeze-backports and volatile-sloppy. Use only selected packages which fits your needs.

[Cuidado] Cuidado

Archive level Release files (see Secção 2.5.3, “Archive level "Release" files”) are used for the rule of apt_preferences(5). Thus apt-pinning works only with "code" name for volatile Debian archives. This is different from other Debian archives. For example, you can do "Pin: release a=squeeze" but can not do "Pin: release a=stable" in the "/etc/apt/preferences" file for volatile Debian archives.

Here is an example of apt-pinning technique to include specific newer upstream version packages found in squeeze-backports while tracking squeeze and volatile. You list all required archives in the "/etc/apt/sources.list" file as the following.

deb http://ftp.us.debian.org/debian/ squeeze main contrib non-free
deb http://security.debian.org/ squeeze/updates main contrib
deb http://volatile.debian.org/debian-volatile/ squeeze/volatile main contrib non-free
deb http://volatile.debian.org/debian-volatile/ squeeze/volatile-sloppy main contrib non-free
deb http://backports.debian.org/debian-backports/ squeeze-backports main contrib non-free

The default Pin-Priority value for backports.debian.org and volatile-sloppy archives are always 1 (<<100) since they are NotAutomatic archive (see Secção 2.5.3, “Archive level "Release" files”). There is no need to set Pin-Priority value explicitly in the "/etc/apt/preferences" file just to use for backports.debian.org and volatile-sloppy archive unless you wish to track packages automatically for next upgrading.

So whenever you wish to install a package named "<package-name>" with its dependency from squeeze-backports archive, you use following command while switching target release with "-t" option.

$ sudo apt-get install -t squeeze-backports <nome_do_pacote>

If you wish to upgrade particular packages, you must create the "/etc/apt/preferences" file and explicitly lists all packages in it as the following.

Package: <package-1>
Pin: release o=Backports.org archive
Pin-Priority: 700

Package: <package-2>
Pin: release o=volatile.debian.org
Pin-Priority: 700

Alternativamente, com o ficheiro "/etc/apt/preferences" como o seguinte.

Package: *
Pin: release a=stable , o=Debian
Pin-Priority: 500

Package: *
Pin: release a=squeeze, o=volatile.debian.org
Pin-Priority: 500

Package: *
Pin: release a=squeeze-backports, o=Backports.org archive
Pin-Priority: 200

Package: *
Pin: release a=squeeze-sloppy, o=volatile.debian.org
Pin-Priority: 200

Execution of "apt-get upgrade" and "apt-get dist-upgrade" (or "aptitude safe-upgrade" and "aptitude full-upgrade") upgrades packages which were installed from stable archive using current stable archive and packages which were installed from other archives using current corresponding archive for all archives in the "/etc/apt/sources.list" file.

2.7.5. Descarga e actualização automática de pacotes

The apt package comes with its own cron script "/etc/cron.daily/apt" to support the automatic download of packages. This script can be enhanced to perform the automatic upgrade of packages by installing the unattended-upgrades package. These can be customized by parameters in "/etc/apt/apt.conf.d/02backup" and "/etc/apt/apt.conf.d/50unattended-upgrades" as described in "/usr/share/doc/unattended-upgrades/README".

The unattended-upgrades package is mainly intended for the security upgrade for the stable system. If the risk of breaking an existing stable system by the automatic upgrade is smaller than that of the system broken by the intruder using its security hole which has been closed by the security update, you should consider using this automatic upgrade with configuration parameters as the following.

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::Unattended-Upgrade "1";

If you are running an unstable system, you do not want to use the automatic upgrade since it certainly breaks system some day. Even for such unstable case, you may still want to download packages in advance to save time for the interactive upgrade with configuration parameters as the following.

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::Unattended-Upgrade "0";

2.7.6. Limitar a largura de banda de descarga para o APT

Se desejar limitar a largura de banda para o APT para por exemplo 800Kib/sec (=100kiB/sec), deve configurar o APT com o seu parâmetro de configuração como o seguinte.

APT::Acquire::http::Dl-Limit "800";

2.7.7. Downgrade de emergência

[Cuidado] Cuidado

Downgrading is not officially supported by the Debian by design. It should be done only as a part of emergency recovery process. Despite of this situation, it is known to work well in many incidents. For critical systems, You should backup all important data on the system after the recovery operation and re-install the new system from the scratch.

You may be lucky to downgrade from newer archive to older archive to recover from broken system upgrade by manipulating candidate version (see Secção 2.7.3, “Tweaking candidate version”). This is lazy alternative to tedious actions of many "dpkg -i <broken-package>_<old-version>.deb" commands (see Secção 2.6.4, “Recuperação com o comando dpkg”).

Search lines in the "/etc/apt/sources.list" file tracking unstable as the following.

deb http://ftp.us.debian.org/debian/ sid main contrib non-free

Replace it with the following to track testing.

deb http://ftp.us.debian.org/debian/ wheezy main contrib non-free

Regule o ficheiro "/etc/apt/preferences" como o seguinte.

Package: *
Pin: release a=testing
Pin-Priority: 1010

Run "apt-get dist-upgrade" to force downgrading of packages across the system.

Remove this special "/etc/apt/preferences" file after this emergency downgrading.

[Dica] Dica

It is good idea to remove (not purge!) as much packages to minimize dependency problems. You may need to manually remove and install some packages to get system downgraded. Linux kernel, bootloader, udev, PAM, APT, and networking related packages and their configuration files require special attention.

2.7.8. Quem enviou o pacote?

Although the maintainer name listed in "/var/lib/dpkg/available" and "/usr/share/doc/package_name/changelog" provide some information on "who is behind the packaging activity", the actual uploader of the package is somewhat obscure. who-uploads(1) in the devscripts package identifies the actual uploader of Debian source packages.

2.7.9. O pacote equivs

If you are to compile a program from source to replace the Debian package, it is best to make it into a real local debianized package (*.deb) and use private archive.

If you chose to compile a program from source and to install them under "/usr/local" instead, you may need to use equivs as a last resort to satisfy the missing package dependency.

Package: equivs
Priority: extra
Section: admin
Description: Circumventing Debian package dependencies
 This is a dummy package which can be used to create Debian
 packages, which only contain dependency information.

2.7.10. Portando um pacote para o sistema stable

For partial upgrades of the stable system, rebuilding a package within its environment using the source package is desirable. This avoids massive package upgrades due to their dependencies.

Add the following entries to the "/etc/apt/sources.list" of a stable system.

deb-src http://http.us.debian.org/debian unstable  main contrib non-free

Instale os pacotes necessários para a compilação e descarregue o pacote fonte como se segue.

# apt-get update
# apt-get dist-upgrade
# apt-get install fakeroot devscripts build-essential
$ apt-get build-dep foo
$ apt-get source foo
$ cd foo*

Ajustar os pacotes instalados se necessário.

Execute o seguinte.

$ dch -i

Bump package version, e.g. one appended with "+bp1" in "debian/changelog"

Compile pacotes e instale-os para o sistema como o seguinte.

$ debuild
$ cd ..
# debi foo*.changes

2.7.11. Servidor proxy para o APT

Since mirroring whole subsection of Debian archive wastes disk space and network bandwidth, deployment of a local proxy server for APT is desirable consideration when you administer many systems on LAN. APT can be configure to use generic web (http) proxy servers such as squid (see Secção 6.10, “Outras aplicações de servidor de rede”) as described in apt.conf(5) and in "/usr/share/doc/apt/examples/configure-index.gz". The "$http_proxy" environment variable can be used to override proxy server setting in the "/etc/apt/apt.conf" file.

There are proxy tools specially for Debian archive. You should check BTS before using them.

Tabela 2.19. Lista de ferramentas proxy especiais para arquivos Debian

pacote popcon tamanho descrição
approx * V:0.3, I:0.3 3896 caching proxy server for Debian archive files (compiled OCaml program)
apt-cacher * V:0.3, I:0.4 308 Caching proxy for Debian package and source files (Perl program)
apt-cacher-ng * V:0.3, I:0.4 1092 Proxy de cache para distribuição de pacotes de software (programa C++ compilado)
debtorrent * V:0.12, I:0.17 1185 Proxy Bittorrent para descarregar pacotes Debian (programa Python)

[Cuidado] Cuidado

When Debian reorganizes its archive structure, these specialized proxy tools tend to require code rewrites by the package maintainer and may not be functional for a while. On the other hand, generic web (http) proxy servers are more robust and easier to cope with such changes.

2.7.12. Pequeno arquivo de pacotes público

Here is an example for creating a small public package archive compatible with the modern secure APT system (see Secção 2.5.2, “Ficheiro "Release" de nível de topo e autenticidade:”). Let's assume few things.

  • nome da conta: "foo"
  • Nome da máquina: "www.example.com"
  • Pacotes requeridos: apt-utils, gnupg, e outros pacotes
  • URL: "http://www.example.com/~foo/" ( → "/home/foo/public_html/index.html")
  • Arquitectura de pacotes: "amd64"

Crie uma chave de arquivo APT de Foo no seu sistema servidor como o seguinte.

$ ssh foo@www.example.com
$ gpg --gen-key
...
$ gpg -K
...
sec   1024D/3A3CB5A6 2008-08-14
uid                  Foo (ARCHIVE KEY) <foo@www.example.com>
ssb   2048g/6856F4A7 2008-08-14
$ gpg --export -a 3A3CB5A6 >foo.public.key

Publica o ficheiro de chave de arquivo "foo.public.key" com o ID de chave "3A3CB5A6" para Foo

Crie uma árvore de arquivo chamada "Origin: Foo" com o seguinte.

$ umask 022
$ mkdir -p ~/public_html/debian/pool/main
$ mkdir -p ~/public_html/debian/dists/unstable/main/binary-amd64
$ mkdir -p ~/public_html/debian/dists/unstable/main/source
$ cd ~/public_html/debian
$ cat > dists/unstable/main/binary-amd64/Release << EOF
Archive: unstable
Version: 4.0
Component: main
Origin: Foo
Label: Foo
Architecture: amd64
EOF
$ cat > dists/unstable/main/source/Release << EOF
Archive: unstable
Version: 4.0
Component: main
Origin: Foo
Label: Foo
Architecture: source
EOF
$ cat >aptftp.conf <<EOF
APT::FTPArchive::Release {
  Origin "Foo";
  Label "Foo";
  Suite "unstable";
  Codename "sid";
  Architectures "amd64";
  Components "main";
  Description "Public archive for Foo";
};
EOF
$ cat >aptgenerate.conf <<EOF
Dir::ArchiveDir ".";
Dir::CacheDir ".";
TreeDefault::Directory "pool/";
TreeDefault::SrcDirectory "pool/";
Default::Packages::Extensions ".deb";
Default::Packages::Compress ". gzip bzip2";
Default::Sources::Compress "gzip bzip2";
Default::Contents::Compress "gzip bzip2";

BinDirectory "dists/unstable/main/binary-amd64" {
  Packages "dists/unstable/main/binary-amd64/Packages";
  Contents "dists/unstable/Contents-amd64";
  SrcPackages "dists/unstable/main/source/Sources";
};

Tree "dists/unstable" {
  Sections "main";
  Architectures "amd64 source";
};
EOF

Você pode automatizar actualizações repetitivas do conteúdo do arquivo APT no seu sistema servidor ao configurar o dupload.

Coloca todos os ficheiros de pacotes em "~foo/public_html/debian/pool/main/" ao executar "dupload -t foo changes_file" no cliente enquanto o "~/.dupload.conf" contém o seguinte.

$cfg{'foo'} = {
  fqdn => "www.example.com",
  method => "scpb",
  incoming => "/home/foo/public_html/debian/pool/main",
  # The dinstall on ftp-master sends emails itself
  dinstall_runs => 1,
};

$cfg{'foo'}{postupload}{'changes'} = "
  echo 'cd public_html/debian ;
  apt-ftparchive generate -c=aptftp.conf aptgenerate.conf;
  apt-ftparchive release -c=aptftp.conf dists/unstable >dists/unstable/Release ;
  rm -f dists/unstable/Release.gpg ;
  gpg -u 3A3CB5A6 -bao dists/unstable/Release.gpg dists/unstable/Release'|
  ssh foo@www.example.com  2>/dev/null ;
  echo 'Package archive created!'";

O script hook postupload inicializado pelo dupload(1) cria ficheiros de arquivo actualizados para cada upload.

Você pode adicionar este pequeno arquivo público à linha de apt do sistema cliente com o seguinte.

$ sudo bash
# echo "deb http://www.example.com/~foo/debian/ unstable main" \
   >> /etc/apt/sources.list
# apt-key add foo.public.key
[Dica] Dica

Se o arquivo está localizado no sistema de ficheiros local, então você pode usar antes o "deb file:///home/foo/debian/ …"

2.7.13. Gravar e copiar a configuração do sistema

Você pode criar um cópia local do estado de selecção de pacotes e debconf com o seguinte.

# dpkg --get-selections '*' > selection.dpkg
# debconf-get-selections    > selection.debconf

Aqui, "*" faz com que "selection.dpkg" também inclua entradas de pacotes para "purgar".

Você pode transferir estes 2 ficheiros para outro computador e instalá-los lá com o seguinte.

# dselect update
# debconf-set-selections < minha_selecção.debconf
# dpkg --set-selections  < minha_selecção.dpkg
# apt-get -u dselect-upgrade    # ou dselect install

Se está a pensar em gerir muitos servidores num cluster com praticamente a mesma configuração, você deve considerar usar um pacote especializado como o fai para gerir o sistema completo.

2.7.14. Converter e instalar um pacote binário alienígena

alien(1) enables the conversion of binary packages provided in Red Hat rpm, Stampede slp, Slackware tgz, and Solaris pkg file formats into a Debian deb package. If you want to use a package from another Linux distribution than the one you have installed on your system, you can use alien to convert it from your preferred package format and install it. alien also supports LSB packages.

[Atenção] Atenção

alien(1) should not be used to replace essential system packages, such as sysvinit, libc6, libpam-modules, etc. Practically, alien(1) should only used for non-free binary-only packages which are LSB compliant or statically linked. For free softwares, you should use their source packages to make real Debian packages.

2.7.15. Extrair um pacote sem o dpkg

Os conteúdos dos pacotes "*.deb" actuais podem ser extraídos sem usar o dpkg(1) em qualquer ambiente estilo Unix usando os standard ar(1) e tar(1).

# ar x /path/to/dpkg_<version>_<arch>.deb
# ls
total 24
-rw-r--r-- 1 bozo bozo  1320 2007-05-07 00:11 control.tar.gz
-rw-r--r-- 1 bozo bozo 12837 2007-05-07 00:11 data.tar.gz
-rw-r--r-- 1 bozo bozo     4 2007-05-07 00:11 debian-binary
# mkdir control
# mkdir data
# tar xvzf control.tar.gz -C control
# tar xvzf data.tar.gz -C data

Também pode explorar o conteúdo de um pacote usando o comando mc.

2.7.16. Mais leituras para a gestão de pacotes

Você pode aprender mais sobre a gestão de pacotes a partir das seguintes documentações.