1082
Referências Debian Osamu Aoki Copyright © 2007-2010 Osamu Aoki Este Debian Reference (v2) (2011-04-15 08:14:11 UTC) destina-se a disponibilizar uma visão geral ampla do sistema Debian como um guia de utilizador pós-instalação. Cobre muitos aspectos da administração do sistema através de exemplos de comandos de consola para não-programadores. Resumo Este livro é livre: você pode redistribuí-lo e/ou modificá-lo sob os termos da licença GNU General Public License de qualquer versão respeitante das directivas Debian Free Software Guidelines (DFSG). ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━━━━ Índice

Referências Debian

Embed Size (px)

Citation preview

Page 1: Referências Debian

Referências Debian

Osamu Aoki

Copyright © 2007-2010 Osamu Aoki

Este Debian Reference (v2) (2011-04-15 08:14:11 UTC) destina-se

a disponibilizar uma visão geral ampla do sistema Debian como um

guia de utilizador pós-instalação. Cobre muitos aspectos da

administração do sistema através de exemplos de comandos de

consola para não-programadores.

Resumo

Este livro é livre: você pode redistribuí-lo e/ou modificá-lo

sob os termos da licença GNU General Public License de qualquer

versão respeitante das directivas Debian Free Software

Guidelines (DFSG).

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Índice

Prefácio

1. Renúncia

2. O que é a Debian

3. Acerca deste documento

Page 2: Referências Debian

3.1. Regras de guia

3.2. Pré-requisitos

3.3. Convenções

3.4. BTS da Debian

3.5. A popcon

3.6. O tamanho do pacote

3.7. Relatórios de bugs neste documento

4. Algumas citações para novos utilizadores

1. Manuais de GNU/Linux

1.1. Bases de consola

1.1.1. A linha de comandos shell

1.1.2. A linha de comandos shell sob X

1.1.3. A conta root

1.1.4. A linha de comandos shell do root

1.1.5. GUIs de ferramentas de administração do sistema

1.1.6. Consolas virtuais

1.1.7. Como abandonar a linha de comandos

1.1.8. Como desligar o sistema

1.1.9. Recuperar uma consola sã

1.1.10. Sugestões de pacote adicionais para o novato

1.1.11. Uma conta de utilizador extra

1.1.12. Configuração do sudo

1.1.13. Hora de brincar

Page 3: Referências Debian

1.2. Sistema de ficheiros tipo Unix

1.2.1. Noções básicas de ficheiros Unix.

1.2.2. Internos do sistema de ficheiros

1.2.3. Permissões do sistema de ficheiros

1.2.4. Control de permissões para ficheiros acabados de

criar: umask

1.2.5. Permissões para grupos de utilizadores (group)

1.2.6. Marcas temporais (Timestamps)

1.2.7. Links (ligações)

1.2.8. Pipes nomeados (FIFOs)

1.2.9. Sockets

1.2.10. Ficheiros de dispositivo

1.2.11. Ficheiros de dispositivos especiais

1.2.12. procfs e sysfs

1.3. Midnight Commander (MC)

1.3.1. Personalização do MC

1.3.2. Arrancar o MC

1.3.3. Gestor de ficheiros em MC

1.3.4. Truques de linha de comandos no MC

1.3.5. O editor interno em MC

1.3.6. O visualizador interno no MC

1.3.7. Funcionalidades de auto-arranque do MC

1.3.8. Sistema de ficheiros FTP virtual no MC

1.4. O ambiente de trabalho estilo Unix básico

Page 4: Referências Debian

1.4.1. A shell de login

1.4.2. Personalizar o bash

1.4.3. Teclas especiais

1.4.4. Operações do rato ao estilo Unix

1.4.5. O pager

1.4.6. O editor de texto

1.4.7. Definir um editor de texto predefinido

1.4.8. Personalizar o vim

1.4.9. Gravar as actividades da shell

1.4.10. Comandos Unix básicos

1.5. O simples comando de shell

1.5.1. Execução de comando e variável de ambiente

1.5.2. variável "$LANG"

1.5.3. variável "$PATH"

1.5.4. variável "$HOME"

1.5.5. Opções de linha de comandos

1.5.6. Glob da shell

1.5.7. Valor de retorno do comando

1.5.8. Sequências de comandos típicas e

redireccionamento da shell

1.5.9. Command alias

1.6. Processamento de texto estilo Unix

1.6.1. Ferramentas de texto de Unix

1.6.2. Expressões regulares

1.6.3. Expressões de substituição

Page 5: Referências Debian

1.6.4. Substituição global com expressões regulares

1.6.5. Extrair dados de tabela de ficheiro de texto

1.6.6. Script snippets for piping commands

2. Gestão de pacotes Debian

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

Page 6: Referências Debian

2.3. Exemplos de operações do aptitude

2.3.1. Listagem de pacotes com correspondência por

expressão regular nos nomes de pacotes

2.3.2. Explorar com a correspondência de expressão

regular

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

Page 7: Referências Debian

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. Updates 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

Page 8: Referências Debian

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

3. A inicialização do sistema

3.1. Uma visão geral do processo de boot strap

3.2. Estágio 1: a BIOS

3.3. Estágio 2: o gestor de arranque

3.4. Estágio 3: o sistema Debian mini

3.5. Estágio 4: o sistema Debian normal

3.5.1. O significado do runlevel

3.5.2. A configuração do runlevel

3.5.3. O exemplo de gestão do runlevel

3.5.4. O parâmetro predefinido para cada script de init

3.5.5. O nome da máquina

3.5.6. O sistema de ficheiros

3.5.7. Inicialização da interface de rede

3.5.8. Inicialização do serviço de rede

3.5.9. A mensagem do sistema

3.5.10. A mensagem do kernel

3.5.11. O sistema udev

3.5.12. A inicialização de módulos do kernel

4. Autenticação

Page 9: Referências Debian

4.1. Autenticação Unix normal

4.2. Gerir informação de conta e palavra-passe

4.3. Boa palavra-passe

4.4. Criando palavra-passe encriptada

4.5. PAM e NSS

4.5.1. Ficheiros de configuração acedidos pelo PAM e NSS

4.5.2. O moderno sistema de gestão centralizado

4.5.3. "Porque o su do GNU não suporta o grupo wheel"

4.5.4. Regras de palavra-passe rigorosas

4.6. Outros controles de acesso

4.6.1. sudo

4.6.2. SELinux

4.6.3. Restringindo acesso a alguns serviços de servidor

4.7. Segurança da autenticação

4.7.1. Palavra-passe segura sobre a Internet

4.7.2. Shell Segura

4.7.3. Medidas de segurança extra para a Internet

4.7.4. Tornar a palavra-passe do root segura

5. Configuração de rede

5.1. A infraestrutura de rede básica

5.1.1. O nome de domínio

Page 10: Referências Debian

5.1.2. A resolução de nome de máquina

5.1.3. O nome da interface de rede

5.1.4. O alcance de endereços de rede para a LAN

5.1.5. O suporte a dispositivos de rede

5.2. A configuração de rede moderna para desktop

5.2.1. Ferramentas GUI de configuração de rede

5.3. A ligação e configuração legacy de rede

5.4. O método de ligação de rede (legacy)

5.4.1. A ligação DHCP com a Ethernet

5.4.2. A ligação de IP estático com a Ethernet

5.4.3. A ligação PPP com o pppconfig

5.4.4. A ligação PPP alternativa com o wvdialconf

5.4.5. A ligação PPPoE com o pppoeconf

5.5. A configuração de rede básica com ifupdown (legacy)

5.5.1. A sintaxe de comando simplificada

5.5.2. A sintaxe básica de "/etc/network/interfaces"

5.5.3. A interface de rede loopback

5.5.4. A interface de rede servida por DHCP

5.5.5. A interface de rede com IP estático

5.5.6. A base da interface LAN wireless

5.5.7. A interface LAN wireless com WPA/WPA2

5.5.8. A interface LAN wireless com WEP

5.5.9. A ligação PPP

Page 11: Referências Debian

5.5.10. A ligação PPP alternativa

5.5.11. A ligação PPPoE

5.5.12. O estado de configuração de rede do ifupdown

5.5.13. A base da configuração de rede

5.5.14. O pacote ifupdown-extra

5.6. A configuração de rede avançada com ifupdown (legacy)

5.6.1. O pacote ifplugd

5.6.2. O pacote ifmetric

5.6.3. A interface virtual

5.6.4. A sintaxe de comando avançada

5.6.5. A estrofe de mapeamento

5.6.6. A configuração de rede comutável manualmente

5.6.7. Usar scripts com o sistema ifupdown

5.6.8. Mapeando com guessnet

5.7. A configuração de rede de baixo nível

5.7.1. Comandos iproute2

5.7.2. Operações de rede seguras de baixo nível

5.8. Optimização da rede

5.8.1. Encontrar o MTU óptimo

5.8.2. Definir o MTU

5.8.3. Optimização WAN TCP

5.9. Infraestrutura do netfilter

Page 12: Referências Debian

6. Aplicações de rede

6.1. Exploradores web

6.1.1. Configuração do explorador

6.2. O sistema de mail (correio electrónico)

6.2.1. Bases dos serviços de mail modernos

6.2.2. A estratégia de configuração de mail para estação

de trabalho

6.3. Agente de transporte de mail (MTA)

6.3.1. A configuração do exim4

6.3.2. A configuração do postfix com SASL

6.3.3. A configuração do endereço de mail

6.3.4. Operações MTA básicas

6.4. Agente utilizador de mail (MUA)

6.4.1. MUA básico — Mutt

6.5. O adquiridor de mail remoto e utilitário de

reencaminhamento

6.5.1. configuração do getmail

6.5.2. configuração do fetchmail

Page 13: Referências Debian

6.6. Agente de entrega de mail (MDA) com filtro

6.6.1. configuração do maildrop

6.6.2. configuração do procmail

6.6.3. Re-entregar o conteúdo da mbox

6.7. Servidor POP3/IMAP4

6.8. O servidor de impressão e utilitário

6.9. O servidor de acesso remoto e utilitário (SSH)

6.9.1. Bases do SSH

6.9.2. Reencaminhamento de portos para SMTP/POP3 em

túnel

6.9.3. Ligar sem palavras-passe remotas

6.9.4. Lidar com clientes SSH alienígenas

6.9.5. Configurar o ssh-agent

6.9.6. Como desligar o sistema remoto em SSH

6.9.7. Depurar problemas no SSH

6.10. Outras aplicações de servidor de rede

6.11. Outros clientes de aplicação de rede

6.12. Os diagnósticos dos daemons do sistema

7. O Sistema X Window

7.1. Pacotes chave

7.2. Definir o ambiente de trabalho

Page 14: Referências Debian

7.2.1. Menu Debian

7.2.2. Menu Freedesktop.org

7.2.3. Menu Debian sob o ambiente de trabalho GNOME

7.3. A relação servidor/cliente

7.4. O servidor X

7.4.1. A (re)configuração do servidor X

7.4.2. Os métodos de ligação do servidor X

7.5. Iniciando o X Window System

7.5.1. Iniciar uma sessão X com o gdm

7.5.2. Personalizar a sessão X (método clássico)

7.5.3. Personalizar a sessão X (método novo)

7.5.4. Ligar um cliente X remoto via SSH

7.5.5. Terminal X seguro via Internet

7.6. Fonts (tipos de letra) para o X Window

7.6.1. Fonts (tipos de letra) básicas

7.6.2. Fonts (tipos de letra) adicionais

7.6.3. fonts CJK

7.7. Aplicações do X

7.7.1. Aplicações de escritório do X

7.7.2. aplicações utilitárias do X

Page 15: Referências Debian

7.8. The X trivia

7.8.1. Mapas de teclas e mapas de botões do apontador

(rato) no X

7.8.2. Clientes X Clássicos

7.8.3. O emulador de terminal X - xterm

7.8.4. Correr clientes X como root

8. I18N e L10N

8.1. A entrada do teclado

8.1.1. O suporte a método de entrada com IBus

8.1.2. Um exemplo para Japonês

8.1.3. Desactivar o método de entrada

8.2. O mostrador de resultados

8.3. O locale

8.3.1. Bases de codificação

8.3.2. Rationale for UTF-8 locale

8.3.3. A reconfiguração do locale

8.3.4. O valor da variável de ambiente "$LANG"

8.3.5. O locale específico apenas sob X Window

8.3.6. Codificação de nomes de ficheiros

8.3.7. Mensagens localizadas e documentação traduzida

8.3.8. Efeitos do locale

9. Dicas do sistema

Page 16: Referências Debian

9.1. O programa screen

9.1.1. O cenário de utilização para o screen(1)

9.1.2. ligações de teclas para o comando screen

9.2. Gravação de dados e apresentação

9.2.1. O daemon de log

9.2.2. Analizador de log

9.2.3. Gravar as actividades da shell de modo limpo

9.2.4. Amostragem personalizada de dados em texto

9.2.5. Amostragem personalizada de hora e data

9.2.6. Echo de shell colorido

9.2.7. Comandos coloridos

9.2.8. Recordando as actividades do editor para

repetições complexas

9.2.9. Gravar a imagem gráfica de uma aplicação X

9.2.10. Gravar alterações em ficheiros de configuração

9.3. Dicas de armazenamento de dados

9.3.1. Configuração das partições do disco

9.3.2. Aceder a partição usando UUID

9.3.3. Configuração do sistema de ficheiros

9.3.4. Criação do sistema de ficheiros e verificação de

integridade

9.3.5. Optimização do sistema de ficheiros por opções de

montagem

Page 17: Referências Debian

9.3.6. Optimização do sistema de ficheiros através do

superblock

9.3.7. Optimização do disco rijo

9.3.8. Usar SMART para prever falhas no disco rijo

9.3.9. Expandir o espaço de armazenamento utilizável via

LVM

9.3.10. Expandir o espaço de armazenamento utilizável ao

montar outra partição

9.3.11. Expandir o espaço de armazenamento utilizável

usando links simbólicos

9.3.12. Expandir o espaço de armazenamento utilizável

usando aufs

9.4. Dicas de encriptação de dados

9.4.1. Encriptação de discos amovíveis com dm-crypt/LUKS

9.4.2. Partição swap encriptada com dm-crypt

9.4.3. Encriptar ficheiro automaticamente com eCryptfs

9.4.4. Montar eCryptfs automaticamente

9.5. Monitorizar, controlar e arrancar as actividades de

programas

9.5.1. Temporizando um processo

9.5.2. A prioridade de agendamento

9.5.3. O comando ps

9.5.4. O comando top

9.5.5. Listar ficheiros abertos por um processo

9.5.6. Rastear as actividades de programas

Page 18: Referências Debian

9.5.7. Identificação de um processo usando ficheiros ou

sockets

9.5.8. Repetir um comando com um intervalo constante

9.5.9. Repeating a command looping over files

9.5.10. Arrancar um programa a partir da GUI

9.5.11. Personalizar o programa a ser arrancado

9.5.12. Matar um processo

9.5.13. Scheduling tasks once

9.5.14. Scheduling tasks regularly

9.5.15. Tecla Alt-SysRq

9.6. Dicas de manutenção do sistema

9.6.1. Quem está no sistema?

9.6.2. Avisar todos

9.6.3. Identificação do hardware

9.6.4. Configuração do hardware

9.6.5. Hora do sistema e do hardware

9.6.6. A configuração do terminal

9.6.7. A infraestrutura de som

9.6.8. Desactivar o protector de écran (screensaver)

9.6.9. Desactivar os sons de beep

9.6.10. Utilização da memória

9.6.11. Segurança do sistema e verificação de

integridade

9.7. O kernel

9.7.1. Kernel Linux 2.6

Page 19: Referências Debian

9.7.2. Parâmetros do kernel

9.7.3. Cabeçalhos do kernel

9.7.4. Compilar o kernel e módulos relacionados

9.7.5. Compilar a fonte do kernel: O método standard da

Debian

9.7.6. Compilar o módulo fontes: O método standard da

Debian

9.7.7. Compilar a fonte do kernel: O método clássico

9.7.8. Drivers de hardware não-livres

9.8. Sistema virtualizado

9.8.1. Ferramentas de virtualização

9.8.2. Fluxo de trabalho da virtualização

9.8.3. Montar o ficheiro de imagem de disco virtual

9.8.4. Sistema chroot

9.8.5. Sistemas de múltiplos ambientes de trabalho

10. Gestão de dados

10.1. Partilhar, copiar e arquivar

10.1.1. Ferramentas de arquivo e compressão

10.1.2. Ferramentas de cópia de sincronização

10.1.3. Idiomas para o arquivo

10.1.4. Idiomas para a cópia

10.1.5. Idiomas para a selecção de ficheiros

10.1.6. Salvaguarda (backup) e recuperação

10.1.7. Suites de utilitários de salvaguardas (backup)

Page 20: Referências Debian

10.1.8. Um script de exemplo para salvaguarda ao sistema

10.1.9. Um script de cópia para a salvaguarda de dados

10.1.10. Dispositivo de armazenamento amovível

10.1.11. Partilhando dados via rede

10.1.12. Media de arquivo

10.2. A imagem de disco

10.2.1. Criando o ficheiro de imagem de disco

10.2.2. Escrever directamente no disco

10.2.3. Montar o ficheiro de imagem de disco

10.2.4. Limpar um ficheiro de imagem de disco

10.2.5. Criar um ficheiro de imagem de disco vazio

10.2.6. Criar o ficheiro de imagem ISO9660

10.2.7. Escrever directamente para o CD/DVD-R/RW

10.2.8. Montar o ficheiro de imagem ISO9660

10.3. Os dados binários

10.3.1. Ver e editar dados binários

10.3.2. Manipular ficheiros sem montar o disco

10.3.3. Redundância de dados

10.3.4. Recuperação de ficheiros e dados e análise

forense

10.3.5. Dividir um ficheiro grande em ficheiros pequenos

10.3.6. Limpar conteúdo de ficheiro

10.3.7. Ficheiros dummy

10.3.8. apagar um disco rijo inteiro

10.3.9. Apagar uma área não utilizada do disco rijo

Page 21: Referências Debian

10.3.10. Recuperar ficheiros apagados mas ainda abertos

10.3.11. Procurar todos os hardlinks

10.3.12. Consumo invisível do espaço do disco

10.4. Infraestrutura da segurança de dados

10.4.1. Gestão de chaves para GnuPG

10.4.2. Usa GnuPG em ficheiros

10.4.3. Usar GnuPG com o Mutt

10.4.4. Usar GnuPG com o Vim

10.4.5. O sumário MD5

10.5. Ferramentas de fusão de código fonte

10.5.1. Extrair as diferenças para ficheiros fonte

10.5.2. Fundir actualizações para ficheiros de fonte

10.5.3. Actualizar via fusão-de-3-vias

10.6. Sistemas de controle de versão

10.6.1. Comparação dos comandos VCS

10.7. CVS

10.7.1. Configuração de repositório CVS

10.7.2. Acesso local ao CVS

10.7.3. Acesso remoto ao CVS com pserver

10.7.4. Acesso remoto ao CVS com ssh

10.7.5. Importar uma nova fonte para o CVS

Page 22: Referências Debian

10.7.6. Permissões de ficheiros no repositório CVS

10.7.7. Fluxo de trabalho do CVS

10.7.8. Ficheiros mais recentes do CVS

10.7.9. Administração do CVS

10.7.10. Execution bit for CVS checkout

10.8. Subversion

10.8.1. Configuration of Subversion repository

10.8.2. Access to Subversion via Apache2 server

10.8.3. Acesso local ao Subversion pelo grupo

10.8.4. Acesso remoto ao Subversion via SSH

10.8.5. Estrutura de directórios do Subversion

10.8.6. importar uma nova fonte para o Subversion

10.8.7. Fluxo de trabalho do Subversion

10.9. Git

10.9.1. Configuração do cliente Git

10.9.2. Referências do Git

10.9.3. Comandos do Git

10.9.4. Git para o repositório Subversion

10.9.5. Git para gravar o histórico de configuração

11. Conversão de dados

11.1. Ferramentas de conversão de dados em texto

11.1.1. Converter um ficheiro de texto com o iconv

Page 23: Referências Debian

11.1.2. Verifica ficheiro se é UTF-8 com o iconv

11.1.3. Converter os nomes dos ficheiros com o iconv

11.1.4. conversão EOL

11.1.5. Conversão de TAB

11.1.6. Editores com auto-conversão

11.1.7. Extracção de texto simples

11.1.8. Highlighting and formatting plain text data

11.2. Dados XML

11.2.1. Dicas básicas para XML

11.2.2. Processamento de XML

11.2.3. A extracção de dados de XML

11.3. Dados imprimíveis

11.3.1. Ghostscript

11.3.2. Fundir dois ficheiros PS ou PDF

11.3.3. Utilitários de dados imprimíveis

11.3.4. Imprimir com o CUPS

11.4. Type setting

11.4.1. roff typesetting

11.4.2. TeX/LaTeX

11.4.3. Impressão bonita de um manual

11.4.4. Criar um manual

11.5. A conversão de dados de mail

Page 24: Referências Debian

11.5.1. Noções básicas de dados de mail

11.6. Ferramentas de dados gráficos

11.7. Conversão de dados variados

12. Programação

12.1. O script shell

12.1.1. Compatibilidade da shell do POSIX

12.1.2. Parâmetros da shell

12.1.3. Condicionais da shell

12.1.4. Ciclos da shell

12.1.5. A sequência de processamento da linha de

comandos da shell

12.1.6. Programas utilitários para script de shell

12.1.7. Diálogo do script de shell

12.1.8. Shell script example with zenity

12.2. Make

12.3. C

12.3.1. Programa C simples (gcc)

12.4. Depuração

12.4.1. Execução gdb básica

12.4.2. Depurar o pacote Debian

Page 25: Referências Debian

12.4.3. Obtaining backtrace

12.4.4. Comandos gdb avançados

12.4.5. Depurar Erros do X

12.4.6. Verificar a dependência em bibliotecas

12.4.7. Ferramentas de detecção de fugas de memória

12.4.8. Ferramentas de análise de código estático

12.4.9. Disassemble binary

12.5. Flex — um Lex melhor.

12.6. Bison — um Yacc melhor

12.7. Autoconf

12.7.1. Compilar e instalar o programa

12.7.2. Desinstalar o programa

12.8. Perl short script madness

12.9. Web

12.10. A tradução do código fonte

12.11. Criando um pacote Debian

A. Apêndice

A.1. o labirinto Debian

A.2. História do Copyright

A.3. Formato do documento

Lista de Tabelas

1.1. Lista de pacotes de programas de modo de texto

Page 26: Referências Debian

interessantes

1.2. Lista de pacotes de documentação informativa

1.3. Lista de utilização de directórios chave

1.4. Lista do primeiro caractere da saída de "ls -l"

1.5. O modo numérico para permissões de ficheiros em comandos

chmod(1)

1.6. Exemplos do valor umask

1.7. Lista de grupos notáveis disponibilizados pelo sistema para

acesso a ficheiros

1.8. Lista de grupos notáveis disponibilizados pelo sistema para

execuções de comandos particulares

1.9. Lista dos tipos de marcas temporais

1.10. Lista de ficheiros de dispositivos especiais

1.11. As teclas de atalho do MC

1.12. A reacção à tecla enter no MC

1.13. Lista de programas da shell

1.14. Lista de teclas de atalho para bash

1.15. Lista de operações de rato ao estilo Unix

1.16. lista dos comandos Unix básicos

1.17. 3 partes do valor locale

1.18. Lista de recomendações de locale

1.19. Lista de valores "$HOME"

1.20. Padrões glob da shell

1.21. Códigos de saída do comando

1.22. Idiomas de comandos de shell

1.23. Predefined file descriptors

1.24. Meta-caracteres para BRE e ERE

1.25. A expressão de substituição

1.26. List of script snippets for piping commands

Page 27: Referências Debian

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

2.2. Lista de sites de arquivos Debian

2.3. Lista de área de arquivo Debian

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

2.5. Lista de sites web chave para resolver problemas com um

pacote específico.

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).

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

2.8. Lista de teclas de atalho do aptitude

2.9. Lista de vistas para o aptitude

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

2.11. Lista da fórmula regex do aptitude

2.12. Os ficheiros log para actividades de pacotes

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

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

2.15. A estrutura de nomes dos pacotes Debian

2.16. Os caracteres utilizáveis para cada componente nos nomes

de pacotes Debian

2.17. Os ficheiros notáveis criados pelo dpkg

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

source type

2.19. Lista de ferramentas proxy especiais para arquivos Debian

3.1. Lista de gestores de arranque

3.2. O significado dos parâmetros do GRUB

3.3. Lista de utilitários de arranque para o sistema Debian

3.4. Lista de runlevels e descrição da sua utilização

3.5. Lista de níveis de erro do kernel

4.1. 3 ficheiros de configuração importantes para pam_unix(8)

Page 28: Referências Debian

4.2. A segunda entrada no conteúdo de "/etc/passwd"

4.3. Lista de comandos para gerir informação de conta

4.4. Lista de ferramentas para gerar palavras-passe

4.5. Lista de sistemas PAM e NSS notáveis

4.6. Lista de ficheiros de configuração acedidos pelo PAM

4.7. Lista de serviços e portos inseguros e seguros

4.8. Lista de ferramentas para disponibilizar medidas de

segurança extra

5.1. Lista de ferramentas de configuração de rede

5.2. Lista de alcances de endereços de rede

5.3. Lista de métodos de ligação de rede e caminhos de ligação

5.4. Lista de configurações de ligação de rede

5.5. Lista de ligações de rede anónimas

5.6. Lista de ficheiros de configuração para a ligação PPP com

pppconfig

5.7. Lista de ficheiros de configuração para a ligação PPP com

wvdialconf

5.8. Lista de ficheiros de configuração para a ligação PPPoE com

pppoeconf

5.9. Lista de comandos de configuração de rede básicos com

ifupdown

5.10. Lista de estrofes em "/etc/network/interfaces"

5.11. Lista de siglas para WLAN

5.12. Lista de terminologia para dispositivos de rede

5.13. Lista de comandos avançados de configuração de rede com

ifupdown

5.14. Lista de variáveis de ambiente passadas pelo sistema

ifupdown

5.15. Tabela de tradução dos comandos obsoletos net-tools para

Page 29: Referências Debian

os novos comandos iproute2

5.16. Lista de comandos de rede de baixo nível

5.17. Lista de ferramentas de optimização de rede

5.18. Regras básicas para o valor MTU óptimo

5.19. Lista de ferramentas de firewall

6.1. Lista de exploradores web

6.2. Lista de pacotes plugin de exploradores

6.3. Lista de pacotes básicos relacionados com agente de

transporte de mail para estação de trabalho

6.4. Lista de escolhas para pacotes de agente de transporte de

mail (MTA) no arquivo Debian.

6.5. Lista dos manuais importantes do postfix

6.6. Lista de ficheiros de configuração relacionados com

endereços de mail

6.7. Lista de operações MTA básicas

6.8. Lista de agentes utilizador de mail (MUA)

6.9. Lista de adquiridores de mail remoto e utilitários de

reencaminhamento

6.10. Lista de MDA com filtro

6.11. Lista de Servidores POP3/IMAP4

6.12. Lista de servidores de impressoras e utilitários

6.13. Lista de servidores de acesso remoto e utilitários

6.14. Lista de protocolos e métodos de autenticação do SSH

6.15. Lista de ficheiros de configuração do SSH

6.16. Lista de exemplos de arranque do cliente SSH

6.17. Lista de clientes SSH para outras plataformas

6.18. Lista de outras aplicações de servidor de rede

6.19. Lista de clientes de aplicação de rede

6.20. Lista de RFCs populares

Page 30: Referências Debian

7.1. Lista de (meta)pacotes chave para o X Window

7.2. Lista de terminologia de servidor/cliente

7.3. Lista de métodos de ligação ao servidor X

7.4. Tabela de pacotes para suportar fonts do sistema X Window

7.5. Tabela de fonts PostScript Type 1 correspondentes

7.6. Tabela de fonts correspondentes a TrueType

7.7. Tabela de palavras chave usadas em nomes de fonts CJK para

indicar os tipos de fonts.

7.8. lista de aplicações X de escritório básicas

7.9. Lista de aplicações X utilitárias básicas

8.1. Lista de métodos de configuração do teclado

8.2. Lista de suportes a método de entrada com IBus

9.1. Lista de programas para suportar ligações à rede

interrompidas

9.2. Lista de ligações de teclas para o écran

9.3. Lista de analisadores de log do sistema

9.4. Mostra exemplos de hora e data para o comando "ls -l" para

lenny

9.5. Lista de ferramentas gráficas de manipulação de imagens

9.6. Lista de pacotes para gravar histórico de configuração em

VCS

9.7. Lista de pacotes de gestão de partições do disco

9.8. Lista de pacotes de gestão de sistemas de ficheiros

9.9. Lista de utilitários de encriptação de dados

9.10. Lista de ferramentas para monitorizar e controlar as

actividades de programas

9.11. Lista de valores nice para a prioridade de agendamento

9.12. Lista dos estilos do comando ps

9.13. Lista de comandos para o top

Page 31: Referências Debian

9.14. Lista dos sinais frequentemente usados para matar comandos

9.15. Lista de teclas de comando SAK

9.16. Lista de ferramenta de identificação de hardware

9.17. Lista de ferramentas de configuração do hardware

9.18. Lista de pacotes de som

9.19. Lista de comandos para desactivar o protector de écran

9.20. Lista dos tamanhos de memória relatados

9.21. Lista de ferramentas para segurança do sistema e

verificação de integridade

9.22. Lista de pacotes chave a serem instalados para a

recompilação do kernel no sistema Debian.

9.23. Lista de ferramentas de virtualização

10.1. Lista de ferramentas de arquivo e compressão

10.2. Lista de ferramentas de cópia e sincronização

10.3. Lista de suites utilitárias de salvaguarda

10.4. Lista de pacotes que permitem aos utilizadores normais

montarem dispositivos amovíveis sem uma entrada

correspondente no "/etc/fstab"

10.5. Lista de hipóteses de sistemas de ficheiros para

dispositivos de armazenamento amovíveis com cenários de

utilização típica

10.6. Lista de serviços de rede para escolher com o cenário de

utilização típico

10.7. Lista de pacote para ver e editar dados binários

10.8. Lista de pacotes para ler e escrever ficheiros sem montar

o disco.

10.9. Lista de ferramentas para adicionar redundância de dados a

ficheiros

10.10. Lista de pacotes para recuperação de ficheiros e dados e

Page 32: Referências Debian

análise forense

10.11. Lista de ferramentas de infraestrutura da segurança de

dados

10.12. Lista de comandos do GNU Privacy Guard para gestão de

chaves

10.13. Lista do significado do código de confiança

10.14. Lista de comandos do GNU Privacy Guard em ficheiros

10.15. Lista de ferramentas de fusão de código fonte

10.16. lista de ferramentas de sistemas de controle de versão

10.17. Comparação dos comandos VCS nativos

10.18. Notable options for CVS commands (use as first argument

(s) to cvs(1))

10.19. Notable options for Subversion commands (use as first

argument(s) to svn(1))

10.20. Lista de pacotes e comandos relacionados com o git

11.1. Lista de ferramentas de conversão de dados em texto

11.2. Lista de valores de codificação e a sua utilização

11.3. Lista de estilos EOL para diferentes plataformas

11.4. List of TAB conversion commands from bsdmainutils and

coreutils packages

11.5. Lista de ferramentas para extracção de dados de texto

simples

11.6. List of tools to highlight plain text data

11.7. Lista de entidades predefinidas para XML

11.8. Lista de ferramentas XML

11.9. Lista de ferramentas DSSL

11.10. Lista de ferramentas de extracção de dados de XML

11.11. Lista de ferramentas de impressão bonita de XML

11.12. List of Ghostscript PostScript interpreters

Page 33: Referências Debian

11.13. Lista de utilitários de dados imprimíveis

11.14. List of type setting tools

11.15. Lista de pacotes para ajudar a criar o manual (manpage)

11.16. Lista de pacotes para ajudar na conversão de dados de

mail

11.17. Lista de ferramentas de dados gráficos

11.18. Lista de ferramentas de conversão de dados variados

12.1. Lista de pacotes para ajudar a programar

12.2. Lista dos bashisms típicos

12.3. Lista de parâmetros da shel

12.4. Lista de expansões de parâmetros de shell

12.5. Lista de substituições de parâmetros de shell chave

12.6. Lista de operadores de comparação de ficheiros na

expressão condicional

12.7. Lista de operadores de comparação de strings na expressão

condicional

12.8. List of packages containing small utility programs for

shell scripts

12.9. Lista de programas de interface de utilizador

12.10. Lista de variáveis automáticas do make

12.11. Lista de expansões da variável do make

12.12. Lista de comandos gdb avançados

12.13. Lista de ferramentas de detecção de fugas de memória

12.14. Lista de ferramentas para análise de código estático

12.15. List of Yacc-compatible LALR parser generators

12.16. Lista de ferramentas de tradução de código fonte

Prefácio

Page 34: Referências Debian

Este Debian Reference (version 2) (2011-04-15 08:14:11 UTC)

destina-se a disponibilizar uma visão geral ampla da

administração do sistema Debian como um guia de utilizador

pós-instalação.

Destina-se ao leitor que é alguém disposto a aprender scripts de

consola mas não está pronto para ler todas as fontes C para

descobrir como o sistema GNU/Linux funciona.

1. Renúncia

Todas as garantias são renunciadas. Todas as marcas são

propriedade dos seus donos de marca respectivos.

O próprio sistema Debian é um alvo em movimento. Isto torna

difícil manter a sua documentação actualizada e correcta. Apesar

de ter sido usada a versão instável actual do sistema Debian

como base para escrever isto, alguns conteúdos podem já estar

ultrapassados quando os estiver a ler.

Por favor veja este documento como uma referência secundária.

Este documento não substitui nenhuns guias oficiais. O autor e

contribuintes não toma responsabilidade pelas consequências de

erros, omissões ou ambiguidade neste documento.

2. O que é a Debian

O Projecto Debian é uma associação de indivíduos que têm como

causa comum a criação de um sistema operativo livre. A sua

Page 35: Referências Debian

distribuição é caracterizada pelo seguinte.

Compromisso com a liberdade do software: Debian Social●

Contract e Debian Free Software Guidelines (DFSG)

Esforço distribuído não-remunerado de voluntários baseado na●

Internet: http://www.debian.org

Grande número de softwares pré-compilados de alta qualidade●

Focado em estabilidade e segurança com acesso fácil a●

actualizações de segurança

Focado na actualização suave aos softwares mais recentes com●

os arquivos unstable e testing

Grande número de arquitecturas de hardware suportadas●

As peças de Free Software em Debian vêm de GNU, Linux, BSD, X,

ISC, Apache, Ghostscript, Common Unix Printing System , Samba,

GNOME, KDE, Mozilla, OpenOffice.org, Vim, TeX, LaTeX, DocBook,

Perl, Python, Tcl, Java, Ruby, PHP, Berkeley DB, MySQL,

PostgreSQL, Exim, Postfix, Mutt, FreeBSD, OpenBSD, Plan 9 e

muitos mais projectos de software livre independentes. Debian

integra esta diversidade de Software Livre em um sistema.

3. Acerca deste documento

3.1. Regras de guia

As seguintes regras de guia foram seguidas ao compilar este

documento.

Fornecer uma visão geral e saltar casos não comuns. (Big●

Page 36: Referências Debian

Picture)

Keep It Short and Simple. (KISS)●

Não reinvente a roda. (Use apontadores para as referências●

existentes)

Foco nas ferramentas não-GUI e consolas. (Use exemplos de●

shell)

Seja objectivo. (Use popcon etc.)●

Dica

Eu tentei elucidar aspectos hierárquicos e níveis baixos do

sistema.

3.2. Pré-requisitos

Atenção

Espera-se que você se esforce a procurar respostas por si

próprio para além deste documento. Este documento apenas oferece

pontos de arranque eficientes.

Você tem de procurar a solução por si a partir de fontes

primárias.

O site Debian em http://www.debian.org para informação geral●

A documentação sob o directório "/usr/share/doc/●

<nome_do_pacote>"

O manual estilo Unix: "dpkg -L <nome_de_pacote> |grep '/man/●

man.*/'"

Page 37: Referências Debian

A página info estilo GNU: "dpkg -L <nome_do_pacote> |grep '/●

info/'"

O relatório de bugs http://bugs.debian.org/<package_name>●

O Debian Wiki em http://wiki.debian.org/ para os tópicos em●

movimento e específicos

Os HOWTOs do The Linux Documentation Project (TLDP) em http:●

//tldp.org/

A Especificação UNIX Singular da Página Oficial do Sistema●

UNIX do Open Group em http://www.unix.org/

A enciclopédia livre de Wikipedia em http://●

www.wikipedia.org/

Nota

Para informação detalhada, você pode precisar de instalar o

pacote de documentação correspondente chamado com um sufixo

"-doc".

3.3. Convenções

Este documento fornece informação através do seguinte estilo de

apresentação simplificado com exemplos de comandos de shell bash

(1).

# <comando na conta do root>

$ <comando na conta do utilizador>

Estes avisos de shell distinguem a conta usada e corresponde a

definir variáveis de ambiente como: "PS1='\$'" e "PS2=' '".

Page 38: Referências Debian

Estes valores são escolhidos para bem da legibilidade deste

documento e não são típicos do sistema instalado actual.

Nota

Veja o significado das variáveis de ambiente "$PS1" e "$PS2" em

bash(1).

A Acção requerida pelo administrador do sistema é escrita em

sentido imperativo, ex. "Carregue na tecla Enter após escrever

cada string de comando na shell."

The description column and similar ones in the table may contain

a noun phrase following the package short description convention

which drops leading articles such as "a" and "the". They may

alternatively contain an infinitive phrase as a noun phrase

without leading "to" following the short command description

convention in manpages. These may look funny to some people but

are my intentional choices of style to keep this documentation

as simple as possible. These Noun phrases do not capitalize

their starting nor end with periods following these short

description convention.

Nota

Substantivos próprios incluindo os nomes de comandos mantêm o

seu caso sem respeitarem a sua localização (não são traduzidos).

A command snippet quoted in a text paragraph is referred by the

Page 39: Referências Debian

typewriter font between double quotation marks, such as

"aptitude safe-upgrade".

Os dados em texto de um ficheiro de configuração citados num

parágrafo de texto são referidos em font de máquina de escrever

entre aspas, tal como "deb-src".

Um comando é referenciado pelo seu nome em font de máquina de

escrever seguido opcionalmente pelo número de secção do seu

manual em parênteses, tal como bash(1). Você é encorajado a

obter informação ao escrever o seguinte.

$ man 1 bash

Um manual é referido pelo seu nome em font de máquina de

escrever seguido pelo seu número de secção do manual em

parênteses, tal como sources.list(5). Você é encorajado a obter

informação ao escrever o seguinte.

$ man 5 sources.list

Uma página info é referenciada pelo recorte do seu comando em

font de máquina de escrever entre aspas, tal como "info make".

Você é encorajado a obter informação ao escrever o seguinte.

$ info make

Um nome de ficheiro é referenciado em font de máquina de

escrever entre aspas, tal como "/etc/passwd". Para os ficheiros

Page 40: Referências Debian

de configuração, você é encorajado a obter informação ao

escrever o seguinte.

$ sensible-pager "/etc/passwd"

Um nome de directório é referenciado em font de máquina de

escrever entre aspas, tal como "/etc/init.d/". Você é encorajado

a explorar o seu conteúdo ao escrever o seguinte.

$ mc "/etc/init.d/"

Um nome de pacote é referenciado pelo seu nome em font de

máquina de escrever, tal como vim. Você é encorajado a obter

informação ao escrever o seguinte.

$ dpkg -L vim

$ apt-cache show vim

$ aptitude show vim

A documentation may indicate its location by the filename in the

typewriter font between double quotation marks, such as "/usr/

share/doc/sysv-rc/README.runlevels.gz" and "/usr/share/doc/

base-passwd/users-and-groups.html"; or by its URL, such as http:

//www.debian.org. You are encouraged to read the documentation

by typing the following.

$ zcat "/usr/share/doc/sysv-rc/README.runlevels.gz" | sensible-pager

$ sensible-browser "/usr/share/doc/base-passwd/users-and-groups.html"

$ sensible-browse "http://www.debian.org"

Page 41: Referências Debian

Uma variável de ambiente é referenciada pelo seu nome com um "$"

inicial em font de máquina de escrever entre aspas, tal como

"$TERM". Você é encorajado a obter o seu valor actual ao

escrever o seguinte.

$ echo "$TERM"

3.4. BTS da Debian

O asterisco "*" colocado logo após cada nome de pacote está

ligado ao Sistema de acompanhamento de bugs da Debian (BTS) de

cada pacote

3.5. A popcon

Os dados popcon são apresentados como a medida objectiva da

popularidade de cada pacote. Foi descarregado em 2010-12-08

14:47:18 UTC e contém a submissão total de 95150 relatórios

sobre 109197 pacotes binários e 19 arquitecturas.

Nota

Por favor note que o arquivo amd64 unstable contém actualmente

apenas 30552 pacotes. Os dados popcon contém relatórios de

muitas instalações de sistemas antigos.

O número de popcon precedido de "V:" para "votos" é calculado

por "100 * (as submissões popcon para o pacote executado

Page 42: Referências Debian

recentemente no PC) / (o total de submissões de popcon)".

O número de popcon precedido de "I:" para "instalações" é

calculado por "100 * (as submissões popcon para o pacote

instalado no PC) / (o total de submissões de popcon)".

Nota

As figuras do popcon não devem ser consideradas como medidas

absolutas da importância dos pacotes. Existem muitos factores

que podem aldrabar as estatísticas. Por exemplo, um sistema que

participa no popcon pode ter directórios montados como o "/bin"

com a opção "noatime" para melhoria da performance do sistema e

efectivamente desactivar os "votos" de tal sistema.

3.6. O tamanho do pacote

The package size data is also presented as the objective measure

for each package. It is based on the "Installed-Size:" reported

by "apt-cache show" or "aptitude show" command (currently on

amd64 architecture for the unstable release). The reported size

is in KiB (Kibibyte = unit for 1024 bytes).

Nota

A package with a small numerical package size may indicate that

the package in the unstable release is a dummy package which

installs other packages with significant contents by the

dependency. The dummy package enables a smooth transition or

Page 43: Referências Debian

split of the package.

Nota

A package size followed by "(*)" indicates that the package in

the unstable release is missing and the package size for the

experimental release is used instead.

3.7. Relatórios de bugs neste documento

Please file bug reports on the debian-reference package using

reportbug(1) if you find any issues on this document. Please

include correction suggestion by "diff -u" to the plain text

version or to the source.

4. Algumas citações para novos utilizadores

Aqui estão algumas citações interessantes da lista de mails de

Debian que podem ajudar a elucidar novos utilizadores.

"Isto é Unix. Dá-lhe corda suficiente para você se●

enforcar." --- Miquel van Smoorenburg <miquels em

cistron.nl>

"Unix É amigo do utilizador... Apenas é selectivo sobre quem●

são os seus amigos." --- Tollef Fog Heen <tollef at add.no>

Capítulo 1. Manuais de GNU/Linux

I think learning a computer system is like learning a new

Page 44: Referências Debian

foreign language. Although tutorial books and documentation are

helpful, you have to practice it yourself. In order to help you

get started smoothly, I elaborate a few basic points.

The powerful design of Debian GNU/Linux comes from the Unix

operating system, i.e., a multiuser, multitasking operating

system. You must learn to take advantage of the power of these

features and similarities between Unix and GNU/Linux.

Don't shy away from Unix oriented texts and don't rely solely on

GNU/Linux texts, as this robs you of much useful information.

Nota

If you have been using any Unix-like system for a while with

command line tools, you probably know everything I explain here.

Please use this as a reality check and refresher.

1.1. Bases de consola

1.1.1. A linha de comandos shell

Upon starting the system, you are presented with the character

based login screen if you did not install X Window System with

the display manager such as gdm. Suppose your hostname is foo,

the login prompt looks as follows.

login de foo:

Page 45: Referências Debian

If you did install a GUI environment such as GNOME or KDE, then

you can get to a login prompt by Ctrl-Alt-F1, and you can return

to the GUI environment via Alt-F7 (see Secção 1.1.6, “Consolas

virtuais” below for more).

No aviso de login, você escreve o seu nome de utilizador, ex

pinguim, e carrega na tecla Enter, depois escreve a sua

palavra-passe e carrega na tecla Enter mais uma vez.

Nota

Seguindo a tradição do Unix, o nome de utilizador e

palavra-passe do sistema Debian são sensíveis a maiúsculas/

minúsculas. O nome de utilizador é geralmente escolhido apenas

em minúsculas. A primeira conta de utilizador é geralmente

criada durante a instalação. Podem ser criadas contas de

utilizador adicionais com adduser(8) pelo root.

O sistema inicia com a mensagem de boas vindas armazenada em "/

etc/motd" (Mensagem do Dia) e apresenta um aviso de comando.

Debian GNU/Linux lenny/sid foo tty1

foo login: pinguim

Password:

Last login: Sun Apr 22 09:29:34 2007 on tty1

Linux snoopy 2.6.20-1-amd64 #1 SMP Sun Apr 15 20:25:49 UTC 2007 x86_64

The programs included with the Debian GNU/Linux system are free software;

the exact distribution terms for each program are described in the

Page 46: Referências Debian

individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent

permitted by applicable law.

foo:~$

Aqui, a parte principal da mensagem de boas vindas pode ser

personalizada ao editar o ficheiro "/etc/motd.tail". A primeira

linha é gerada a partir de informação do sistema usando "uname

-snrvm".

Agora você está na shell. A shell interpreta os seus comandos.

1.1.2. A linha de comandos shell sob X

If you installed X Window System with a display manager such as

GNOME's gdm by selecting "Desktop environment" task during the

installation, you are presented with the graphical login screen

upon starting your system. You type your username and your

password to login to the non-privileged user account. Use tab to

navigate between username and password, or use the mouse and

primary click.

You can gain the shell prompt under X by starting a

x-terminal-emulator program such as gnome-terminal(1), rxvt(1)

or xterm(1). Under the GNOME Desktop environment, clicking

"Applications" → "Accessories" → "Terminal" does the trick.

Pode ver também a secção abaixo Secção 1.1.6, “Consolas

Page 47: Referências Debian

virtuais”.

Under some other Desktop systems (like fluxbox), there may be no

obvious starting point for the menu. If this happens, just try

(right) clicking the center of the screen and hope for a menu to

pop-up.

1.1.3. A conta root

The root account is also called superuser or privileged user.

From this account, you can perform the following system

administration tasks.

Lê, escreve e remove quaisquer ficheiros no sistema●

independentemente das suas permissões

Define o dono e permissões de quaisquer ficheiros no sistema●

Define a palavra-passe de quaisquer utilizadores não●

privilegiados do sistema.

Login em quaisquer contas sem as suas palavras-passe●

Este poder ilimitado da conta root querer que você seja

atencioso e responsável quando a usa.

Atenção

Nunca partilhe a palavra-passe de root com outros.

Nota

Page 48: Referências Debian

File permissions of a file (including hardware devices such as

CD-ROM etc. which are just another file for the Debian system)

may render it unusable or inaccessible by non-root users.

Although the use of root account is a quick way to test this

kind of situation, its resolution should be done through proper

setting of file permissions and user's group membership (see

Secção 1.2.3, “Permissões do sistema de ficheiros”).

1.1.4. A linha de comandos shell do root

Aqui estão alguns métodos básicos de ganhar o aviso de shell de

root ao usar a palavra-passe do root.

Escreva root no aviso de login baseado em caracteres.●

Clique "Aplicações" → "Acessórios" → "Terminal de Root", sob●

o ambiente de trabalho GNOME.

Escreva "su -l" no aviso de shell de qualquer utilizador.●

Isto não preserva o ambiente do utilizador actual.○

Escreva "su" no aviso de shell de qualquer utilizador.●

Isto preserva algum do ambiente do utilizador actual.○

1.1.5. GUIs de ferramentas de administração do sistema

When your desktop menu does not start GUI system administration

tools automatically with the appropriate privilege, you can

start them from the root shell prompt of the X terminal

emulator, such as gnome-terminal(1), rxvt(1), or xterm(1). See

Page 49: Referências Debian

Secção 1.1.4, “A linha de comandos shell do root” and

Secção 7.8.4, “Correr clientes X como root”.

Atenção

Never start the X display/session manager under the root account

by typing in root to the prompt of the display manager such as

gdm(1).

Atenção

Never run untrusted remote GUI program under X Window when

critical information is displayed since it may eavesdrop your X

screen.

1.1.6. Consolas virtuais

In the default Debian system, there are six switchable

VT100-like character consoles available to start the command

shell directly on the Linux host. Unless you are in a GUI

environment, you can switch between the virtual consoles by

pressing the Left-Alt-key and one of the F1 — F6 keys

simultaneously. Each character console allows independent login

to the account and offers the multiuser environment. This

multiuser environment is a great Unix feature, and very

addictive.

If you are under the X Window System, you gain access to the

character console 1 by pressing Ctrl-Alt-F1 key, i.e., the

Page 50: Referências Debian

left-Ctrl-key, the left-Alt-key, and the F1-key are pressed

together. You can get back to the X Window System, normally

running on the virtual console 7, by pressing Alt-F7.

Você pode alternativamente mudar para outra consola virtual, por

exemplo para a consola 1, a partir da linha de comandos.

# chvt 1

1.1.7. Como abandonar a linha de comandos

You type Ctrl-D, i.e., the left-Ctrl-key and the d-key pressed

together, at the command prompt to close the shell activity. If

you are at the character console, you return to the login prompt

with this. Even though these control characters are referred as

"control D" with the upper case, you do not need to press the

Shift-key. The short hand expression, ^D, is also used for

Ctrl-D. Alternately, you can type "exit".

Se você está no emulador-terminal-x(1), você pode fechar a

janela do emulador-terminal-x com isto.

1.1.8. Como desligar o sistema

Just like any other modern OS where the file operation involves

caching data in memory for improved performance, the Debian

system needs the proper shutdown procedure before power can

safely be turned off. This is to maintain the integrity of

files, by forcing all changes in memory to be written to disk.

Page 51: Referências Debian

If the software power control is available, the shutdown

procedure automatically turns off power of the system.

(Otherwise, you may have to press power button for few seconds

after the shutdown procedure.)

Você pode desligar o sistema sob o modo normal de

multi-utilizador a partir da linha de comandos.

# shutdown -h now

Você pode desligar o sistema sob o modo único-utilizador a

partir da linha de comandos.

# poweroff -i -f

Alternatively, you may type Ctrl-Alt-Delete (The left-Ctrl-key,

the left-Alt-Key, and the Delete are pressed together) to

shutdown if "/etc/inittab" contains "ca:12345:ctrlaltdel:/sbin/

shutdown -t1 -a -h now" in it. See inittab(5) for details.

Veja Secção 6.9.6, “Como desligar o sistema remoto em SSH”.

1.1.9. Recuperar uma consola sã

When the screen goes berserk after doing some funny things such

as "cat <some-binary-file>", type "reset" at the command prompt.

You may not be able to see the command echoed as you type. You

may also issue "clear" to clean up the screen.

Page 52: Referências Debian

1.1.10. Sugestões de pacote adicionais para o novato

Although even the minimal installation of the Debian system

without any desktop environment tasks provides the basic Unix

functionality, it is a good idea to install few additional

commandline and curses based character terminal packages such as

mc and vim with apt-get(8) for beginners to get started by the

following.

# apt-get update

...

# apt-get install mc vim sudo

...

Se você já tiver estes pacotes instalados, não serão instalados

novos pacotes.

Tabela 1.1. Lista de pacotes de programas de modo de texto

interessantes

┌────────┬──────┬───────┬──────────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├────────┼──────┼───────┼──────────────────────────────────────┤

mc * V:12, 6508 Um gestor de ficheiro de écran │ │ │ │ │

I:28 completo em modo de texto │ │ │ │ │

├────────┼──────┼───────┼──────────────────────────────────────┤

sudo * V:42, 668 Um programa que permite privilégios de│ │ │ │ │

Page 53: Referências Debian

I:71 root limitados aos utilizadores │ │ │ │ │

├────────┼──────┼───────┼──────────────────────────────────────┤

V:15, O editor de texto de Unix Vi IMproved,│ │ │ │ │

vim * I:33 1792 um editor de texto de programadores │ │ │ │ │

(versão standard) │ │ │ │ │

├────────┼──────┼───────┼──────────────────────────────────────┤

vim-tiny V:16, O editor de texto de Unix Vi IMproved,│ │ │ │ │

* I:92 776 um editor de texto de programadores │ │ │ │ │

(versão compacta) │ │ │ │ │

├────────┼──────┼───────┼──────────────────────────────────────┤

emacs23 V:3, O Projecto Emacs do GNU, o editor de │ │ │ │ │

* I:4 13016 texto extensível baseado no Lisp │ │ │ │ │

(versão 23) │ │ │ │ │

├────────┼──────┼───────┼──────────────────────────────────────┤

w3m * V:24, 1992 Exploradores WWW de modo de texto │ │ │ │ │

I:84 │ │ │ │ │

├────────┼──────┼───────┼──────────────────────────────────────┤

gpm * V:3, 484 O cortar-e-colar estilo Unix na │ │ │ │ │

I:4 consola de texto (daemon) │ │ │ │ │

└────────┴──────┴───────┴──────────────────────────────────────┘

Pode ser uma boa ideia ler algumas documentações informativas.

Tabela 1.2. Lista de pacotes de documentação informativa

Page 54: Referências Debian

┌────────────────────┬──────┬───────┬──────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├────────────────────┼──────┼───────┼──────────────────────────┤

Documentação do Projecto │ │ │ │ │

doc-debian * I:82 408 Debian, (FAQ da Debian) e │ │ │ │ │

outros documentos │ │ │ │ │

├────────────────────┼──────┼───────┼──────────────────────────┤

debian-policy * I:3 3500 Manual de Politicas Debian│ │ │ │ │

e documentos relacionados │ │ │ │ │

├────────────────────┼──────┼───────┼──────────────────────────┤

developers-reference I:1.0 1388 Guias e informação para │ │ │ │ │

* programadores de Debian │ │ │ │ │

├────────────────────┼──────┼───────┼──────────────────────────┤

maint-guide * I:0.7 776 Guia dos Novos Maintainers│ │ │ │ │

de Debian │ │ │ │ │

├────────────────────┼──────┼───────┼──────────────────────────┤

debian-history * I:0.3 3736 História do Projecto │ │ │ │ │

Debian │ │ │ │ │

├────────────────────┼──────┼───────┼──────────────────────────┤

debian-faq * I:66 1224 FAQ da Debian │ │ │ │ │

├────────────────────┼──────┼───────┼──────────────────────────┤

doc-linux-text * I:82 8616 Manuais de Linux e FAQ │ │ │ │ │

(texto) │ │ │ │ │

Page 55: Referências Debian

├────────────────────┼──────┼───────┼──────────────────────────┤

doc-linux-html * I:0.7 62564 Manuais de Linux e FAQ │ │ │ │ │

(html) │ │ │ │ │

├────────────────────┼──────┼───────┼──────────────────────────┤

sysadmin-guide * I:0.2 964 O Guia do Administrador de│ │ │ │ │

Sistema Debian │ │ │ │ │

└────────────────────┴──────┴───────┴──────────────────────────┘

Você pode instalar alguns destes pacotes com o seguinte.

# apt-get install nome_do_pacote

1.1.11. Uma conta de utilizador extra

Se você não deseja usar a sua conta de utilizador principal para

as seguintes actividades de treino, você pode criar uma conta de

utilizador para treinos, por exemplo fish fazendo o seguinte.

# adduser fish

Responder a todas as questões.

Isto cria uma nova conta chamada fish. Após praticar, você pode

remover esta conta de utilizador e o seu directório home fazendo

o seguinte.

Page 56: Referências Debian

# deluser --remove-home fish

1.1.12. Configuração do sudo

For the typical single user workstation such as the desktop

Debian system on the laptop PC, it is common to deploy simple

configuration of sudo(8) as follows to let the non-privileged

user, e.g. penguin, to gain administrative privilege just with

his user password but without the root password.

# echo "penguin ALL=(ALL) ALL" >> /etc/sudoers

Alternativamente, é também comum fazer como se segue para

permitir a um utilizador não privilegiado, ex. penguin, ganhar

privilégios administrativos sem qualquer palavra-passe.

# echo "penguin ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers

Este truque só deve ser usado na estação de trabalho de um único

utilizador o qual você administra e onde você é o único

utilizador.

Atenção

Não configure assim as contas de utilizadores normais numa

estação de trabalho de multi-utilizadores porque seria muito mau

para a segurança do sistema.

Cuidado

Page 57: Referências Debian

The password and the account of the penguin in the above example

requires as much protection as the root password and the root

account.

Cuidado

Administrative privilege in this context belongs to someone

authorized to perform the system administration task on the

workstation. Never give some manager in the Admin department of

your company or your boss such privilege unless they are

authorized and capable.

Nota

For providing access privilege to limited devices and limited

files, you should consider to use group to provide limited

access instead of using the root privilege via sudo(8).

Nota

With more thoughtful and careful configuration, sudo(8) can

grant limited administrative privileges to other users on a

shared system without sharing the root password. This can help

with accountability with hosts with multiple administrators so

you can tell who did what. On the other hand, you might not want

anyone else to have such privileges.

1.1.13. Hora de brincar

Page 58: Referências Debian

Agora você está pronto para brincar com o sistema Debian sem

riscos desde que use a conta de utilizador sem-privilégios.

This is because the Debian system is, even after the default

installation, configured with proper file permissions which

prevent non-privileged users from damaging the system. Of

course, there may still be some holes which can be exploited but

those who worry about these issues should not be reading this

section but should be reading Securing Debian Manual.

Nós aprendemos o sistema Debian como um sistema tipo Unix com o

seguinte.

Secção 1.2, “Sistema de ficheiros tipo Unix” (conceitos●

básicos)

Secção 1.3, “Midnight Commander (MC)” (método de●

sobrevivência)

Secção 1.4, “O ambiente de trabalho estilo Unix básico”●

(método básico)

Secção 1.5, “O simples comando de shell” (mecanismo da●

shell)

Secção 1.6, “Processamento de texto estilo Unix” (método de●

processamento de texto)

1.2. Sistema de ficheiros tipo Unix

In GNU/Linux and other Unix-like operating systems, files are

organized into directories. All files and directories are

Page 59: Referências Debian

arranged in one big tree rooted at "/". It's called a tree

because if you draw the filesystem, it looks like a tree but it

is upside down.

These files and directories can be spread out over several

devices. mount(8) serves to attach the filesystem found on some

device to the big file tree. Conversely, umount(8) detaches it

again. On recent Linux kernels, mount(8) with some options can

bind part of a file tree somewhere else or can mount filesystem

as shared, private, slave, or unbindable. Supported mount

options for each filesystem are available in "/share/doc/

linux-doc-2.6.*/Documentation/filesystems/".

Directories on Unix systems are called folders on some other

systems. Please also note that there is no concept for drive

such as "A:" on any Unix system. There is one filesystem, and

everything is included. This is a huge advantage compared to

Windows.

1.2.1. Noções básicas de ficheiros Unix.

Aqui estão algumas noções básicas de ficheiros Unix.

Os nomes de ficheiro são sensíveis a maiúsculas/minúsculas.●

Isto é, "MEUFICHEIRO" e "MeuFicheiro" são ficheiros

diferentes.

The root directory means root of the filesystem referred as●

simply "/". Don't confuse this with the home directory for

the root user: "/root".

Page 60: Referências Debian

Every directory has a name which can contain any letters or●

symbols except "/". The root directory is an exception; its

name is "/" (pronounced "slash" or "the root directory") and

it cannot be renamed.

Each file or directory is designated by a fully-qualified●

filename, absolute filename, or path, giving the sequence of

directories which must be passed through to reach it. The

three terms are synonymous.

All fully-qualified filenames begin with the "/" directory,●

and there's a "/" between each directory or file in the

filename. The first "/" is the top level directory, and the

other "/"'s separate successive subdirectories, until we

reach the last entry which is the name of the actual file.

The words used here can be confusing. Take the following

fully-qualified filename as an example: "/usr/share/

keytables/us.map.gz". However, people also refers to its

basename "us.map.gz" alone as a filename.

The root directory has a number of branches, such as "/etc/"●

and "/usr/". These subdirectories in turn branch into still

more subdirectories, such as "/etc/init.d/" and "/usr/local/

". The whole thing viewed collectively is called the

directory tree. You can think of an absolute filename as a

route from the base of the tree ("/") to the end of some

branch (a file). You also hear people talk about the

directory tree as if it were a family tree: thus

subdirectories have parents, and a path shows the complete

ancestry of a file. There are also relative paths that begin

somewhere other than the root directory. You should remember

that the directory "../" refers to the parent directory.

Page 61: Referências Debian

This terminology also applies to other directory like

structures, such as hierarchical data structures.

There's no special directory path name component that●

corresponds to a physical device, such as your hard disk.

This differs from RT-11, CP/M, OpenVMS, MS-DOS, AmigaOS, and

Microsoft Windows, where the path contains a device name

such as "C:\". (However, directory entries do exist that

refer to physical devices as a part of the normal

filesystem. See Secção 1.2.2, “Internos do sistema de

ficheiros”.)

Nota

While you can use almost any letters or symbols in a file name,

in practice it is a bad idea to do so. It is better to avoid any

characters that often have special meanings on the command line,

including spaces, tabs, newlines, and other special characters:

{ } ( ) [ ] ' ` " \ / > < | ; ! # & ^ * % @ $ . If you want to

separate words in a name, good choices are the period, hyphen,

and underscore. You could also capitalize each word, "LikeThis".

Experienced Linux users tend to avoid spaces in filenames.

Nota

A palavra "root" pode significar o "utilizador root" ou o

"directório raiz (root)". O contexto da sua utilização deve

torná-lo claro.

Nota

Page 62: Referências Debian

The word path is used not only for fully-qualified filename as

above but also for the command search path. The intended meaning

is usually clear from the context.

The detailed best practices for the file hierarchy are described

in the Filesystem Hierarchy Standard ("/usr/share/doc/

debian-policy/fhs/fhs-2.3.txt.gz" and hier(7)). You should

remember the following facts as the starter.

Tabela 1.3. Lista de utilização de directórios chave

┌──────────┬───────────────────────────────────────────────────┐

directório utilização do directório │ │ │

├──────────┼───────────────────────────────────────────────────┤

/ o directório raiz │ │ │

├──────────┼───────────────────────────────────────────────────┤

/etc/ ficheiros de configuração de todo o sistema │ │ │

├──────────┼───────────────────────────────────────────────────┤

/var/log/ ficheiros log do sistema │ │ │

├──────────┼───────────────────────────────────────────────────┤

/home/ todos os directórios home de todos os utilizadores │ │ │

não privilegiados. │ │ │

└──────────┴───────────────────────────────────────────────────┘

Page 63: Referências Debian

1.2.2. Internos do sistema de ficheiros

Following the Unix tradition, the Debian GNU/Linux system

provides the filesystem under which physical data on hard disks

and other storage devices reside, and the interaction with the

hardware devices such as console screens and remote serial

consoles are represented in an unified manner under "/dev/".

Each file, directory, named pipe (a way two programs can share

data), or physical device on a Debian GNU/Linux system has a

data structure called an inode which describes its associated

attributes such as the user who owns it (owner), the group that

it belongs to, the time last accessed, etc. If you are really

interested, see "/usr/include/linux/fs.h" for the exact

definition of "struct inode" in the Debian GNU/Linux system. The

idea of representing just about everything in the filesystem was

a Unix innovation, and modern Linux kernels have developed this

idea ever further. Now, even information about processes running

in the computer can be found in the filesystem.

This abstract and unified representation of physical entities

and internal processes is very powerful since this allows us to

use the same command for the same kind of operation on many

totally different devices. It is even possible to change the way

the kernel works by writing data to special files that are

linked to running processes.

Dica

Page 64: Referências Debian

Se precisar de identificar a correspondência entre a árvore de

ficheiros e a entrada física, execute mount(8) sem argumentos.

1.2.3. Permissões do sistema de ficheiros

Filesystem permissions of Unix-like system are defined for three

categories of affected users.

O utilizador que é dono do ficheiro (u)●

Other users in the group which the file belongs to (g)●

All other users (o) also referred to as "world" and●

"everyone"

Para o ficheiro, cada permissão correspondente permite as

seguintes acções.

A permissão read (r) permite ao dono examinar o conteúdo do●

ficheiro.

A permissão write (w) permite ao dono modificar o ficheiro.●

A permissão execute (x) permite ao dono correr o ficheiro●

como um comando.

Para o directório, cada permissão correspondente permite as

seguintes acções.

A permissão read (r) permite ao dono listar o conteúdo do●

directório.

A permissão write (w) permite ao dono adicionar ou remover●

Page 65: Referências Debian

ficheiros no directório.

A permissão execute (x) permite ao dono aceder aos ficheiro●

no directório.

Here, the execute permission on a directory means not only to

allow reading of files in that directory but also to allow

viewing their attributes, such as the size and the modification

time.

ls(1) is used to display permission information (and more) for

files and directories. When it is invoked with the "-l" option,

it displays the following information in the order given.

Tipo de ficheiro (primeiro caractere)●

Permissão de acesso do ficheiro (nove caracteres,●

consistindo de três caracteres cada para utilizador, grupo,

e os outros por esta ordem)

Número de hard links para o ficheiro●

Nome do utilizador que é dono do ficheiro●

Nome do grupo ao qual o ficheiro pertence●

Tamanho do ficheiro em caracteres (bytes)●

Data e hora do ficheiro (mtime)●

Nome do ficheiro●

Tabela 1.4. Lista do primeiro caractere da saída de "ls -l"

┌─────────┬──────────────────────────────┐

caractere significado │ │ │

├─────────┼──────────────────────────────┤

Page 66: Referências Debian

- ficheiro normal │ │ │

├─────────┼──────────────────────────────┤

d directório │ │ │

├─────────┼──────────────────────────────┤

l link simbólico │ │ │

├─────────┼──────────────────────────────┤

c nó de dispositivo de caractere│ │ │

├─────────┼──────────────────────────────┤

b nó de dispositivo de bloco │ │ │

├─────────┼──────────────────────────────┤

p pipe nomeado │ │ │

├─────────┼──────────────────────────────┤

s socket │ │ │

└─────────┴──────────────────────────────┘

chown(1) is used from the root account to change the owner of

the file. chgrp(1) is used from the file's owner or root account

to change the group of the file. chmod(1) is used from the

file's owner or root account to change file and directory access

permissions. Basic syntax to manipulate a foo file is the

following.

# chown <novo_dono> foo

# chgrp <novo_grupo> foo

# chmod [ugoa][+-=][rwxXst][,...] foo

For example, you can make a directory tree to be owned by a user

foo and shared by a group bar by the following.

Page 67: Referências Debian

# cd /qualquer/localização/

# chown -R foo:bar .

# chmod -R ug+rwX,o=rX .

Existem mais três bits de permissão especiais.

The set user ID bit (s or S instead of user's x)●

The set group ID bit (s or S instead of group's x)●

The sticky bit (t or T instead of other's x)●

Here the output of "ls -l" for these bits is capitalized if

execution bits hidden by these outputs are unset.

Setting set user ID on an executable file allows a user to

execute the executable file with the owner ID of the file (for

example root). Similarly, setting set group ID on an executable

file allows a user to execute the executable file with the group

ID of the file (for example root). Because these settings can

cause security risks, enabling them requires extra caution.

Setting set group ID on a directory enables the BSD-like file

creation scheme where all files created in the directory belong

to the group of the directory.

Setting the sticky bit on a directory prevents a file in the

directory from being removed by a user who is not the owner of

the file. In order to secure contents of a file in

world-writable directories such as "/tmp" or in group-writable

Page 68: Referências Debian

directories, one must not only reset the write permission for

the file but also set the sticky bit on the directory.

Otherwise, the file can be removed and a new file can be created

with the same name by any user who has write access to the

directory.

Aqui estão alguns exemplos interessantes de permissões de

ficheiros.

$ ls -l /etc/passwd /etc/shadow /dev/ppp /usr/sbin/exim4

crw------- 1 root root 108, 0 2007-04-29 07:00 /dev/ppp

-rw-r--r-- 1 root root 1427 2007-04-16 00:19 /etc/passwd

-rw-r----- 1 root shadow 943 2007-04-16 00:19 /etc/shadow

-rwsr-xr-x 1 root root 700056 2007-04-22 05:29 /usr/sbin/exim4

$ ls -ld /tmp /var/tmp /usr/local /var/mail /usr/src

drwxrwxrwt 10 root root 4096 2007-04-29 07:59 /tmp

drwxrwsr-x 10 root staff 4096 2007-03-24 18:48 /usr/local

drwxrwsr-x 4 root src 4096 2007-04-27 00:31 /usr/src

drwxrwsr-x 2 root mail 4096 2007-03-28 23:33 /var/mail

drwxrwxrwt 2 root root 4096 2007-04-29 07:11 /var/tmp

There is an alternative numeric mode to describe file

permissions with chmod(1). This numeric mode uses 3 to 4 digit

wide octal (radix=8) numbers.

Tabela 1.5. O modo numérico para permissões de ficheiros em

comandos chmod(1)

Page 69: Referências Debian

┌─────────────┬────────────────────────────────────────────────┐

digito significado │ │ │

├─────────────┼────────────────────────────────────────────────┤

1º digito sum of set user ID (=4), set group ID (=2), and │ │ │

opcional sticky bit (=1) │ │ │

├─────────────┼────────────────────────────────────────────────┤

2º digito sum of read (=4), write (=2), and execute (=1) │ │ │

permissions for user │ │ │

├─────────────┼────────────────────────────────────────────────┤

3º digito idem para grupo │ │ │

├─────────────┼────────────────────────────────────────────────┤

4º digito idem para outros │ │ │

└─────────────┴────────────────────────────────────────────────┘

Isto parece complicado mas na verdade é bastante simples. Se

observar as primeiras colunas (2-10) do resultado do comando "ls

-l" e lê-las como uma representação binária (radix=2) das

permissões do ficheiros ("-" sendo "0" e "rwx" sendo "1"), os

últimos três dígitos do valor de modo numérico para si deverão

fazer sentido como uma representação octal (radix=8) das

permissões do ficheiro.

Por exemplo, tente o seguinte

Page 70: Referências Debian

$ touch foo bar

$ chmod u=rw,go=r foo

$ chmod 644 bar

$ ls -l foo bar

-rw-r--r-- 1 penguin penguin 17 2007-04-29 08:22 bar

-rw-r--r-- 1 penguin penguin 12 2007-04-29 08:22 foo

Dica

If you need to access information displayed by "ls -l" in shell

script, you should use pertinent commands such as test(1), stat

(1) and readlink(1). The shell builtin such as "[" or "test" may

be used too.

1.2.4. Control de permissões para ficheiros acabados de criar:

umask

As permissões que são aplicadas ao criar ficheiros e directórios

novos é restringida pelo comando embutido da shell umask. Veja

dash(1), bash(1), e builtins(7).

(permissões de ficheiros) = (permissões de ficheiros pedidas) & ~(valor umask)

Tabela 1.6. Exemplos do valor umask

┌─────┬────────────────┬─────────────────┬─────────────────────┐

permissões do permissões do │ │ │ │ │

umask ficheiro criadas directório utilização │ │ │ │ │

Page 71: Referências Debian

criadas │ │ │ │ │

├─────┼────────────────┼─────────────────┼─────────────────────┤

apenas pode ser │ │ │ │ │

0022 -rw-r--r-- -rwxr-xr-x escrito pelo │ │ │ │ │

utilizador │ │ │ │ │

├─────┼────────────────┼─────────────────┼─────────────────────┤

0002 -rw-rw-r-- -rwxrwxr-x pode ser escrito pelo│ │ │ │ │

grupo │ │ │ │ │

└─────┴────────────────┴─────────────────┴─────────────────────┘

The Debian system uses a user private group (UPG) scheme as its

default. A UPG is created whenever a new user is added to the

system. A UPG has the same name as the user for which it was

created and that user is the only member of the UPG. UPG scheme

makes it is safe to set umask to 0002 since every user has their

own private group. (In some Unix variants, it is quite common to

setup all normal users belonging to a single users group and is

good idea to set umask to 0022 for security in such cases.)

1.2.5. Permissões para grupos de utilizadores (group)

De modo a fazer com que as permissões de um grupo sejam

aplicadas a um determinado utilizador, esse utilizador precisa

de se tornar um membro do grupo usando "sudo vigr".

Nota

Page 72: Referências Debian

Alternatively, you may dynamically add users to groups during

the authentication process by adding "auth optional

pam_group.so" line to "/etc/pam.d/common-auth" and setting "/etc

/security/group.conf". (See Capítulo 4, Autenticação.)

Os dispositivos de hardware são apenas outro tipo de ficheiros

no sistema Debian. Se tiver problemas a aceder a dispositivos

como o CD-ROM e memórias USB a partir de uma conta de

utilizador, você deve tornar esse utilizador um membro do grupo

relevante.

Alguns grupos notáveis disponibilizados pelo sistema permitem

aos seus membros aceder a ficheiros e dispositivos particulares

sem privilégios de root.

Tabela 1.7. Lista de grupos notáveis disponibilizados pelo

sistema para acesso a ficheiros

┌───────┬──────────────────────────────────────────────────────┐

grupo descrição para ficheiros e dispositivos acessíveis │ │ │

├───────┼──────────────────────────────────────────────────────┤

dialout acesso completo e directo a portas série ("/dev/ttyS │ │ │

[0-3]") │ │ │

├───────┼──────────────────────────────────────────────────────┤

dip Acesso limitado a portas série para ligação Dialup IP │ │ │

a peers de confiança │ │ │

Page 73: Referências Debian

├───────┼──────────────────────────────────────────────────────┤

cdrom drives CD-ROM, DVD+/-RW │ │ │

├───────┼──────────────────────────────────────────────────────┤

audio dispositivo de áudio │ │ │

├───────┼──────────────────────────────────────────────────────┤

video dispositivo de vídeo │ │ │

├───────┼──────────────────────────────────────────────────────┤

scanner scanner(s) │ │ │

├───────┼──────────────────────────────────────────────────────┤

adm logs (relatórios) de monitorização do sistema │ │ │

├───────┼──────────────────────────────────────────────────────┤

staff alguns directórios para trabalho administrativo │ │ │

júnior: "/usr/local", "/home" │ │ │

└───────┴──────────────────────────────────────────────────────┘

Dica

You need to belong to the dialout group to reconfigure modem,

dial anywhere, etc. But if root creates pre-defined

configuration files for trusted peers in "/etc/ppp/peers/", you

only need to belong to the dip group to create Dialup IP

connection to those trusted peers using pppd(8), pon(1), and

poff(1) commands.

Page 74: Referências Debian

Alguns grupos notáveis disponibilizados pelo sistema permitem

aos seus membros executar comandos particulares sem privilégios

de root.

Tabela 1.8. Lista de grupos notáveis disponibilizados pelo

sistema para execuções de comandos particulares

┌───────┬──────────────────────────────────────────────────────┐

grupo comandos acessíveis │ │ │

├───────┼──────────────────────────────────────────────────────┤

sudo executa sudo sem a sua palavra-passe │ │ │

├───────┼──────────────────────────────────────────────────────┤

lpadmin executa comandos para adicionar, modificar e remover │ │ │

impressoras das bases de dados de impressoras │ │ │

├───────┼──────────────────────────────────────────────────────┤

plugdev executa pmount(1) para dispositivos amovíveis tal como│ │ │

as memórias USB │ │ │

└───────┴──────────────────────────────────────────────────────┘

For the full listing of the system provided users and groups,

see the recent version of the "Users and Groups" document in "/

usr/share/doc/base-passwd/users-and-groups.html" provided by the

base-passwd package.

Veja passwd(5), group(5), shadow(5), newgrp(1), vipw(8), vigr

Page 75: Referências Debian

(8), and pam_group(8) para comandos de gestão para o sistema de

utilizador e grupo.

1.2.6. Marcas temporais (Timestamps)

Existem três tipos de marcas temporais para um ficheiro de GNU/

Linux.

Tabela 1.9. Lista dos tipos de marcas temporais

┌─────┬──────────────────────────────────────────────────┐

tipo significado │ │ │

├─────┼──────────────────────────────────────────────────┤

mtime a hora de modificação do ficheiro (ls -l) │ │ │

├─────┼──────────────────────────────────────────────────┤

ctime a hora de alteração de estado do ficheiro (ls -lc)│ │ │

├─────┼──────────────────────────────────────────────────┤

atime a hora do último acesso ao ficheiro (ls -lu) │ │ │

└─────┴──────────────────────────────────────────────────┘

Nota

ctime não é o tempo de criação do ficheiro.

Sobrescrever um ficheiro altera todos os atributos mtime,●

Page 76: Referências Debian

ctime, and atime do ficheiro.

Alterar o dono ou as permissões de um ficheiro altera os●

atributos ctime e atime do ficheiro.

Ler um ficheiro altera o atime do ficheiro.●

Nota

Even simply reading a file on the Debian system normally causes

a file write operation to update atime information in the inode.

Mounting a filesystem with "noatime" or "relatime" option makes

the system skip this operation and results in faster file access

for the read. This is often recommended for laptops, because it

reduces hard drive activity and saves power. See mount(8).

Use o comando touch(1) para alterar as marcas temporais de

ficheiros existentes.

For timestamps, the ls command outputs different strings under

the modern English locale ("en_US.UTF-8") from under the old one

("C").

$ LANG=en_US.UTF-8 ls -l foo

-rw-r--r-- 1 penguin penguin 3 2008-03-05 00:47 foo

$ LANG=C ls -l foo

-rw-r--r-- 1 penguin penguin 3 Mar 5 00:47 foo

Dica

Veja Secção 9.2.5, “Amostragem personalizada de hora e data”

Page 77: Referências Debian

para personalizar a saída do "ls -l".

1.2.7. Links (ligações)

Existem dois métodos de associar um ficheiro "foo" com um nome

de ficheiro diferente "bar".

Hard link●

Duplica o nome para um ficheiro existente○

"ln foo bar"○

Link Simbólico ou symlink●

Ficheiro especial que aponta para outro ficheiro pelo○

nome

"ln -s foo bar"○

Veja o seguinte exemplo para alterações nas contagens do link e

as diferenças subtis nos resultados do comando rm.

$ echo "Conteúdo Original" > foo

$ ls -li foo

2398521 -rw-r--r-- 1 penguin penguin 17 2007-04-29 08:15 foo

$ ln foo bar # hard link

$ ln -s foo baz # symlink

$ ls -li foo bar baz

2398521 -rw-r--r-- 2 penguin penguin 17 2007-04-29 08:15 bar

2398538 lrwxrwxrwx 1 penguin penguin 3 2007-04-29 08:16 baz -> foo

2398521 -rw-r--r-- 2 penguin penguin 17 2007-04-29 08:15 foo

Page 78: Referências Debian

$ rm foo

$ echo "Novo Conteúdo" > foo

$ ls -li foo bar baz

2398521 -rw-r--r-- 1 penguin penguin 17 2007-04-29 08:15 bar

2398538 lrwxrwxrwx 1 penguin penguin 3 2007-04-29 08:16 baz -> foo

2398540 -rw-r--r-- 1 penguin penguin 12 2007-04-29 08:17 foo

$ cat bar

Conteúdo Original

$ cat baz

Novo Conteúdo

O hardlink pode ser feito dentro do mesmo sistema de ficheiros e

partilhar o mesmo número de inode que o ls(1) com a opção "-i"

revela.

O link simbólico tem sempre permissões nominais de acesso ao

ficheiro "rwxrwxrwx", como mostrado no exemplo em cima, com as

permissões de acesso efectivas ditadas pelas permissões do

ficheiro para o qual aponta.

Cuidado

Geralmente é boa ideia não criar links simbólicos complicados ou

hardlinks de todo a menos que tenha uma boa razão. Podem causar

pesadelos onde a combinação lógica dos links simbólicos resulta

em ciclos viciosos no sistema de ficheiros.

Nota

Page 79: Referências Debian

Geralmente é preferível usar links simbólicos em vez de hard

links, a menos que tenha boas razões para usar um hardlink.

O directório "." liga ao directório onde ele aparece, assim a

contagem de link de qualquer novo directório começa em 2. O

directório ".." liga ao directório pai, assim a contagem de link

do directório aumenta com a adição de novos sub-directórios.

If you are just moving to Linux from Windows, it soon becomes

clear how well-designed the filename linking of Unix is,

compared with the nearest Windows equivalent of "shortcuts".

Because it is implemented in the filesystem, applications can't

see any difference between a linked file and the original. In

the case of hardlinks, there really is no difference.

1.2.8. Pipes nomeados (FIFOs)

A named pipe is a file that acts like a pipe. You put something

into the file, and it comes out the other end. Thus it's called

a FIFO, or First-In-First-Out: the first thing you put in the

pipe is the first thing to come out the other end.

If you write to a named pipe, the process which is writing to

the pipe doesn't terminate until the information being written

is read from the pipe. If you read from a named pipe, the

reading process waits until there is nothing to read before

terminating. The size of the pipe is always zero --- it does not

store data, it just links two processes like the shell "|".

However, since this pipe has a name, the two processes don't

Page 80: Referências Debian

have to be on the same command line or even be run by the same

user. Pipes were a very influential innovation of Unix.

Por exemplo, tente o seguinte

$ cd; mkfifo mypipe

$ echo "hello" >mypipe & # put into background

[1] 8022

$ ls -l mypipe

prw-r--r-- 1 penguin penguin 0 2007-04-29 08:25 mypipe

$ cat mypipe

hello

[1]+ Done echo "hello" >mypipe

$ ls mypipe

mypipe

$ rm mypipe

1.2.9. Sockets

Sockets are used extensively by all the Internet communication,

databases, and the operating system itself. It is similar to the

named pipe (FIFO) and allows processes to exchange information

even between different computers. For the socket, those

processes do not need to be running at the same time nor to be

running as the children of the same ancestor process. This is

the endpoint for the inter process communication (IPC). The

exchange of information may occur over the network between

different hosts. The two most common ones are the Internet

socket and the Unix domain socket.

Page 81: Referências Debian

Dica

"netstat -an" disponibiliza uma visão geral muito útil dos

sockets que estão abertos num determinado sistema.

1.2.10. Ficheiros de dispositivo

Device files refer to physical or virtual devices on your

system, such as your hard disk, video card, screen, or keyboard.

An example of a virtual device is the console, represented by "/

dev/console".

Existem 2 tipos de ficheiros de dispositivo

Dispositivo de Caractere●

Acedido a um caractere de cada vez○

1 caractere = 1 byte○

Ex, teclado, porta série, ...○

Dispositivo de Bloco●

acedido em unidades maiores chamadas blocos○

1 bloco > 1 byte○

Ex, o disco rijo, ...○

You can read and write device files, though the file may well

contain binary data which may be an incomprehensible-to-humans

gibberish. Writing data directly to these files is sometimes

Page 82: Referências Debian

useful for the troubleshooting of hardware connections. For

example, you can dump a text file to the printer device "/dev/

lp0" or send modem commands to the appropriate serial port "/dev

/ttyS0". But, unless this is done carefully, it may cause a

major disaster. So be cautious.

Nota

Para o acesso normal a uma impressora, use lp(1).

Os números de nós de dispositivo são mostrados ao executar ls(1)

como se segue.

$ ls -l /dev/hda /dev/ttyS0 /dev/zero

brw-rw---- 1 root cdrom 3, 0 2007-04-29 07:00 /dev/hda

crw-rw---- 1 root dialout 4, 64 2007-04-29 07:00 /dev/ttyS0

crw-rw-rw- 1 root root 1, 5 2007-04-29 07:00 /dev/zero

"/dev/hda" has the major device number 3 and the minor●

device number 0. This is read/write accessible by the user

who belongs to cdrom group.

"/dev/ttyS0" has the major device number 4 and the minor●

device number 64. This is read/write accessible by the user

who belongs to dialout group.

"/dev/zero" tem o número 1 no maior dispositivo e o número 5●

no menor dispositivo. Isto é acessível para leitura/escrita

por todos.

No sistema Linux 2.6, o sistema de ficheiro sob "/dev/" é

Page 83: Referências Debian

povoado automaticamente pelo mecanismo udev(7).

1.2.11. Ficheiros de dispositivos especiais

Existem alguns ficheiros de dispositivos especiais.

Tabela 1.10. Lista de ficheiros de dispositivos especiais

┌───────────┬────────┬─────────────────────────────────────────┐

ficheiro de acção descrição da resposta │ │ │ │

dispositivo │ │ │ │

├───────────┼────────┼─────────────────────────────────────────┤

/dev/null ler retorna o "caractere de fim-de-ficheiro │ │ │ │

(EOF)" │ │ │ │

├───────────┼────────┼─────────────────────────────────────────┤

/dev/null escrever retorna nada (um poço de despejo de dados│ │ │ │

sem fundo) │ │ │ │

├───────────┼────────┼─────────────────────────────────────────┤

/dev/zero ler retorna "o caractere \0 (NULO) (não é o │ │ │ │

mesmo que o número zero em ASCII) │ │ │ │

├───────────┼────────┼─────────────────────────────────────────┤

return random characters from a true │ │ │ │

/dev/random ler random number generator, delivering real │ │ │ │

entropy (slow) │ │ │ │

├───────────┼────────┼─────────────────────────────────────────┤

Page 84: Referências Debian

/dev/ return random characters from a │ │ │ │

urandom ler cryptographically secure pseudorandom │ │ │ │

number generator │ │ │ │

├───────────┼────────┼─────────────────────────────────────────┤

/dev/full escrever retorna o erro de disco cheiro (ENOSPC) │ │ │ │

└───────────┴────────┴─────────────────────────────────────────┘

Estes são usados frequentemente em conjunto com o

redireccionamento da shell (veja Secção 1.5.8, “Sequências de

comandos típicas e redireccionamento da shell”).

1.2.12. procfs e sysfs

The procfs and sysfs mounted on "/proc" and "/sys" are the

pseudo-filesystem and expose internal data structures of the

kernel to the userspace. In other word, these entries are

virtual, meaning that they act as a convenient window into the

operation of the operating system.

The directory "/proc" contains (among other things) one

subdirectory for each process running on the system, which is

named after the process ID (PID). System utilities that access

process information, such as ps(1), get their information from

this directory structure.

The directories under "/proc/sys/" contain interface to change

certain kernel parameters at run time. (You may do the same

Page 85: Referências Debian

through specialized sysctl(8) command or its preload/

configuration file "/etc/sysctrl.conf".)

Nota

The Linux kernel may complain "Too many open files". You can fix

this by increasing "file-max" value to a larger value from the

root shell, e.g., "echo "65536" > /proc/sys/fs/file-max" (This

was needed on older kernels).

As pessoas entram em pânico frequentemente quando notam num

ficheiro em particular - "/proc/kcore" - o qual é geralmente

enorme. Isto é (mais ou menos) uma cópia do conteúdo da memória

do seu computador. É usado para depurar o kernel. É um ficheiro

virtual que aponta para a memória do computador, portanto não se

preocupe com o seu tamanho.

The directory under "/sys" contains exported kernel data

structures, their attributes, and their linkages between them.

It also contains interface to change certain kernel parameters

at run time.

See "proc.txt(.gz)", "sysfs.txt(.gz)" and other related

documents in the Linux kernel documentation ("/usr/share/doc/

linux-doc-2.6.*/Documentation/filesystems/*") provided by the

linux-doc-2.6.* package.

1.3. Midnight Commander (MC)

Page 86: Referências Debian

Midnight Commander (MC) é um "Canivete Suíço" do GNU para a

consola Linux e outros ambientes de terminal. Isto oferece a

novatos uma experiência de consola movida a menus o que é mais

fácil de aprender que os comandos standard do Unix.

Você deve precisar de instalar o pacote Midnight Commander que é

intitulado de "mc" com o seguinte.

$ sudo apt-get install mc

use o comando mc(1) para explorar o sistema Debian. Esta é a

melhor maneira de aprender. Por favor explore algumas

localizações interessantes apenas usando as teclas do cursor e

Enter.

"/etc" e os seus sub-directórios●

e"/var/log" os seus sub-directórios●

"/usr/share/doc" os seus sub-directórios●

"/sbin" e "/bin"●

1.3.1. Personalização do MC

De modo a fazer o MC mudar o directório de trabalho ao sair e cd

para o directório, eu sugiro modificar o "~/.bashrc" para

incluir um script disponibilizado pelo pacote mc.

. /usr/share/mc/bin/mc.sh

Veja mc(1) (sob a opção "-P") para a razão. (Se você não

Page 87: Referências Debian

compreende exactamente o que estou a falar aqui, pode fazer isto

mais tarde.)

1.3.2. Arrancar o MC

O MC pode ser arrancado com o seguinte.

$ mc

MC takes care of all file operations through its menu, requiring

minimal user effort. Just press F1 to get the help screen. You

can play with MC just by pressing cursor-keys and function-keys.

Nota

In some consoles such as gnome-terminal(1), key strokes of

function-keys may be stolen by the console program. You can

disable these features by "Edit" → "Keyboard Shortcuts" for

gnome-terminal.

Se encontrar problemas com a codificação de caracteres que

mostram caracteres de lixo, adicionar "-a" à linha de comandos

do MC pode ajudar a prevenir problemas.

Se isto não limpar os seus problemas de écran com o MC, veja

Secção 9.6.6, “A configuração do terminal”.

1.3.3. Gestor de ficheiros em MC

Page 88: Referências Debian

The default is two directory panels containing file lists.

Another useful mode is to set the right window to "information"

to see file access privilege information, etc. Following are

some essential keystrokes. With the gpm(8) daemon running, one

can use a mouse on Linux character consoles, too. (Make sure to

press the shift-key to obtain the normal behavior of cut and

paste in MC.)

Tabela 1.11. As teclas de atalho do MC

┌───────────┬──────────────────────────────────────────────────┐

tecla tecla de atalho │ │ │

├───────────┼──────────────────────────────────────────────────┤

F1 menu de ajuda │ │ │

├───────────┼──────────────────────────────────────────────────┤

F3 visualizador de ficheiros interno │ │ │

├───────────┼──────────────────────────────────────────────────┤

F4 editor interno │ │ │

├───────────┼──────────────────────────────────────────────────┤

F9 activa o menu de desenrolar │ │ │

├───────────┼──────────────────────────────────────────────────┤

F10 sair do Midnight Commander │ │ │

├───────────┼──────────────────────────────────────────────────┤

Tab mover entre duas janelas │ │ │

Page 89: Referências Debian

├───────────┼──────────────────────────────────────────────────┤

Insert ou marca o ficheiro para uma operação de múltiplos │ │ │

Ctrl-T ficheiros como uma cópia │ │ │

├───────────┼──────────────────────────────────────────────────┤

Del apaga o ficheiro (tenha cuidado -- configure o MC │ │ │

para modo de apagar seguro) │ │ │

├───────────┼──────────────────────────────────────────────────┤

Teclas do auto-explicativo │ │ │

cursor │ │ │

└───────────┴──────────────────────────────────────────────────┘

1.3.4. Truques de linha de comandos no MC

O comando cd altera o directório mostrado no ecrã●

seleccionado.

Ctrl-Enter ou Alt-Enter copia um nome de ficheiro para a●

linha de comandos, Use isto com os comandos cp(1) e mv(1) em

conjunto com a edição de linha de comandos.

Alt-Tab mostra escolhas de expansão de nomes de ficheiros da●

shell.

Pode-se especificar os directórios de inicio para ambas●

janelas como argumentos ao MC; por exemplo, "mc /etc /root".

Esc + n-key → Fn (i.e., Esc + 1 → F1, etc.; Esc + 0 → F10)●

Pressing Esc before the key has the same effect as pressing●

the Alt and the key together.; i.e., type Esc + c for Alt-C.

Esc is called meta-key and sometimes noted as "M-".

Page 90: Referências Debian

1.3.5. O editor interno em MC

The internal editor has an interesting cut-and-paste scheme.

Pressing F3 marks the start of a selection, a second F3 marks

the end of selection and highlights the selection. Then you can

move your cursor. If you press F6, the selected area is moved to

the cursor location. If you press F5, the selected area is

copied and inserted at the cursor location. F2 saves the file.

F10 gets you out. Most cursor keys work intuitively.

Este editor pode ser iniciado directamente num ficheiro usando

um dos seguintes comandos.

$ mc -e ficheiro_a_editar

$ mcedit ficheiro_a_editar

This is not a multi-window editor, but one can use multiple

Linux consoles to achieve the same effect. To copy between

windows, use Alt-F<n> keys to switch virtual consoles and use

"File→Insert file" or "File→Copy to file" to move a portion of a

file to another file.

Este editor interno pode ser substituído por qualquer editor

externo à escolha.

Also, many programs use the environment variables "$EDITOR" or

"$VISUAL" to decide which editor to use. If you are

Page 91: Referências Debian

uncomfortable with vim(1) or nano(1) initially, you may set

these to "mcedit" by adding the following lines to "~/.bashrc".

export EDITOR=mcedit

export VISUAL=mcedit

Eu recomendo definir isto para "vim" se possível.

Se você fica desconfortável com o vim(1), você pode continuar a

usar o mcedit(1) para a maioria das tarefas de manutenção do

sistema.

1.3.6. O visualizador interno no MC

MC is a very smart viewer. This is a great tool for searching

words in documents. I always use this for files in the "/usr/

share/doc" directory. This is the fastest way to browse through

masses of Linux information. This viewer can be directly started

using one of the following commands.

$ mc -v caminho/para/nome_de_ficheiro_a_visualizar

$ mcview caminho/para/nome_de_ficheiro_a_visualizar

1.3.7. Funcionalidades de auto-arranque do MC

Carregue em Enter num ficheiro, e o programa apropriado lida com

o conteúdo do ficheiro (veja Secção 9.5.11, “Personalizar o

programa a ser arrancado”). Esta é uma funcionalidade muito

Page 92: Referências Debian

conveniente do MC.

Tabela 1.12. A reacção à tecla enter no MC

┌───────────────────────┬──────────────────────────────────────┐

tipo de ficheiro reacção à tecla enter │ │ │

├───────────────────────┼──────────────────────────────────────┤

ficheiro executável executa comando │ │ │

├───────────────────────┼──────────────────────────────────────┤

ficheiro man canaliza o conteúdo para software de │ │ │

visualização │ │ │

├───────────────────────┼──────────────────────────────────────┤

ficheiro html canaliza o conteúdo para explorador │ │ │

web │ │ │

├───────────────────────┼──────────────────────────────────────┤

ficheiros "*.tar.gz" e explora o seu conteúdo como sendo um │ │ │

"*.deb" sub-directório │ │ │

└───────────────────────┴──────────────────────────────────────┘

In order to allow these viewer and virtual file features to

function, viewable files should not be set as executable. Change

their status using chmod(1) or via the MC file menu.

1.3.8. Sistema de ficheiros FTP virtual no MC

Page 93: Referências Debian

MC can be used to access files over the Internet using FTP. Go

to the menu by pressing F9, then type "p" to activate the FTP

virtual filesystem. Enter a URL in the form

"username:[email protected]", which retrieves a remote

directory that appears like a local one.

Tente "[http.us.debian.org/debian]" como URL e explore o arquivo

Debian.

1.4. O ambiente de trabalho estilo Unix básico

Apesar do MC lhe permitir fazer quase tudo, é muito importante

aprender a usar as ferramentas de linha de comandos invocadas do

aviso de shell e torna-se familiarizado com o ambiente de

trabalho estilo Unix.

1.4.1. A shell de login

Você pode seleccionar a sua shell de login com chsh(1).

Tabela 1.13. Lista de programas da shell

┌──────┬───────┬───────┬──────┬────────────────────────────────┐

Shell │ │ │ │ │ │

pacote popcon tamanho do descrição │ │ │ │ │ │

POSIX │ │ │ │ │ │

├──────┼───────┼───────┼──────┼────────────────────────────────┤

Page 94: Referências Debian

bash * V:91, 3536 Sim Bash: a GNU Bourne Again SHell │ │ │ │ │ │

I:99 (o standard de facto) │ │ │ │ │ │

├──────┼───────┼───────┼──────┼────────────────────────────────┤

tcsh * V:4, 768 Não Shell TENEX C: uma versão │ │ │ │ │ │

I:27 melhorada de Berkeley csh │ │ │ │ │ │

├──────┼───────┼───────┼──────┼────────────────────────────────┤

dash * V:25, 248 Sim Shell Alquimista da Debian. bom │ │ │ │ │ │

I:32 para script de shell │ │ │ │ │ │

├──────┼───────┼───────┼──────┼────────────────────────────────┤

zsh * V:3, 12784 Sim Z shell: a shell standard com │ │ │ │ │ │

I:6 muitos melhoramentos │ │ │ │ │ │

├──────┼───────┼───────┼──────┼────────────────────────────────┤

pdksh V:0.2, 468 Sim versão de domínio público da │ │ │ │ │ │

* I:1.1 Korn shell │ │ │ │ │ │

├──────┼───────┼───────┼──────┼────────────────────────────────┤

csh * V:0.6, 404 Não OpenBSD shell C, uma versão do │ │ │ │ │ │

I:2 Berkeley csh │ │ │ │ │ │

├──────┼───────┼───────┼──────┼────────────────────────────────┤

V:0.2, Shell standalone com comandos │ │ │ │ │ │

sash * I:1.0 856 Sim embutidos (Não destinado para "/│ │ │ │ │ │

bin/sh" standard) │ │ │ │ │ │

├──────┼───────┼───────┼──────┼────────────────────────────────┤

ksh * V:0.5, 2800 Sim a versão AT&T real do Korn shell│ │ │ │ │ │

I:1.6 │ │ │ │ │ │

Page 95: Referências Debian

├──────┼───────┼───────┼──────┼────────────────────────────────┤

rc * V:0.16, 204 Não implementação do rc shell AT&T │ │ │ │ │ │

I:1.6 Plan 9 │ │ │ │ │ │

├──────┼───────┼───────┼──────┼────────────────────────────────┤

posh * V:0.01, 228 Sim Policy-compliant Ordinary SHell │ │ │ │ │ │

I:0.11 (derivação da pdksh) │ │ │ │ │ │

└──────┴───────┴───────┴──────┴────────────────────────────────┘

Neste capítulo do tutorial, a shell interactiva significa sempre

bash.

1.4.2. Personalizar o bash

Você pode personalizar o comportamento do bash(1) no "~

/.bashrc".

por exemplo, tente o seguinte.

# CD ao MC existente

. /usr/share/mc/bin/mc.sh

# define CDPATH para uma correcta

CDPATH=.:/usr/share/doc:~:~/Desktop:~

export CDPATH

PATH="${PATH}":/usr/sbin:/sbin

Page 96: Referências Debian

# define PATH para incluir binários privados do utilizador, caso existam

if [ -d ~/bin ] ; then

PATH=~/bin:"${PATH}"

fi

export PATH

EDITOR=vim

export EDITOR

Dica

Você pode encontrar mais dicas de personalização da bash, como

os Secção 9.2.7, “Comandos coloridos”, em Capítulo 9, Dicas do

sistema.

1.4.3. Teclas especiais

In the Unix-like environment, there are few key strokes which

have special meanings. Please note that on a normal Linux

character console, only the left-hand Ctrl and Alt keys work as

expected. Here are few notable key strokes to remember.

Tabela 1.14. Lista de teclas de atalho para bash

┌──────────────────────────┬───────────────────────────────────┐

tecla descrição do atalho da tecla │ │ │

├──────────────────────────┼───────────────────────────────────┤

Ctrl-U apaga a linha antes do cursor │ │ │

Page 97: Referências Debian

├──────────────────────────┼───────────────────────────────────┤

Ctrl-H apaga um caractere antes do cursor │ │ │

├──────────────────────────┼───────────────────────────────────┤

Ctrl-D termina a entrada (sai da shell se │ │ │

estiver a usar uma shell) │ │ │

├──────────────────────────┼───────────────────────────────────┤

Ctrl-C termina um programa em │ │ │

funcionamento │ │ │

├──────────────────────────┼───────────────────────────────────┤

Ctrl-Z temporarily stop program by moving │ │ │

it to the background job │ │ │

├──────────────────────────┼───────────────────────────────────┤

Ctrl-S pára a saída para o écran │ │ │

├──────────────────────────┼───────────────────────────────────┤

Ctrl-Q reactiva a saída para o écran │ │ │

├──────────────────────────┼───────────────────────────────────┤

Ctrl-Alt-Del reinicia/pára o sistema, veja │ │ │

inittab(5) │ │ │

├──────────────────────────┼───────────────────────────────────┤

Left-Alt-key meta-tecla para o Emacs e a UI │ │ │

(opcionalmente, semelhante │ │ │

tecla-do-Windows) │ │ │

├──────────────────────────┼───────────────────────────────────┤

Seta-para-cima inicia a busca no histórico de │ │ │

Page 98: Referências Debian

comandos sob bash │ │ │

├──────────────────────────┼───────────────────────────────────┤

Ctrl-R start incremental command history │ │ │

search under bash │ │ │

├──────────────────────────┼───────────────────────────────────┤

Tab complete input of the filename to │ │ │

the command line under bash │ │ │

├──────────────────────────┼───────────────────────────────────┤

Ctrl-V Tab input Tab without expansion to the │ │ │

command line under bash │ │ │

└──────────────────────────┴───────────────────────────────────┘

Dica

The terminal feature of Ctrl-S can be disabled using stty(1).

1.4.4. Operações do rato ao estilo Unix

As operações do rato ao estilo Unix são baseadas em sistema de

rato de 3 botões.

Tabela 1.15. Lista de operações de rato ao estilo Unix

┌──────────────────────────┬───────────────────────────────────┐

acção resposta │ │ │

Page 99: Referências Debian

├──────────────────────────┼───────────────────────────────────┤

Clique-esquerdo-e-arrastar seleccionar e copiar para a área de│ │ │

do rato transferência │ │ │

├──────────────────────────┼───────────────────────────────────┤

Clique-esquerdo selecciona o início da selecção │ │ │

├──────────────────────────┼───────────────────────────────────┤

Clique-direito selecciona o fim da selecção e │ │ │

copia para a área de transferência │ │ │

├──────────────────────────┼───────────────────────────────────┤

Clique-central cola a área de transferência no │ │ │

cursor │ │ │

└──────────────────────────┴───────────────────────────────────┘

The center wheel on the modern wheel mouse is considered middle

mouse button and can be used for middle-click. Clicking left and

right mouse buttons together serves as the middle-click under

the 2 button mouse system situation. In order to use a mouse in

Linux character consoles, you need to have gpm(8) running as

daemon.

1.4.5. O pager

less(1) is the enhanced pager (file content browser). Hit "h"

for help. It can do much more than more(1) and can be

supercharged by executing "eval $(lesspipe)" or "eval $

Page 100: Referências Debian

(lessfile)" in the shell startup script. See more in "/usr/share

/doc/lessf/LESSOPEN". The "-R" option allows raw character

output and enables ANSI color escape sequences. See less(1).

1.4.6. O editor de texto

You should become proficient in one of variants of Vim or Emacs

programs which are popular in the Unix-like system.

I think getting used to Vim commands is the right thing to do,

since Vi-editor is always there in the Linux/Unix world.

(Actually, original vi or new nvi are programs you find

everywhere. I chose Vim instead for newbie since it offers you

help through F1 key while it is similar enough and more

powerful.)

If you chose either Emacs or XEmacs instead as your choice of

the editor, that is another good choice indeed, particularly for

programming. Emacs has a plethora of other features as well,

including functioning as a newsreader, directory editor, mail

program, etc. When used for programming or editing shell

scripts, it intelligently recognizes the format of what you are

working on, and tries to provide assistance. Some people

maintain that the only program they need on Linux is Emacs. Ten

minutes learning Emacs now can save hours later. Having the GNU

Emacs manual for reference when learning Emacs is highly

recommended.

All these programs usually come with tutoring program for you to

Page 101: Referências Debian

learn them by practice. Start Vim by typing "vim" and press

F1-key. You should at least read the first 35 lines. Then do the

online training course by moving cursor to "|tutor|" and

pressing Ctrl-].

Nota

Good editors, such as Vim and Emacs, can be used to handle UTF-8

and other exotic encoding texts correctly with proper option in

the x-terminal-emulator on X under UTF-8 locale with proper font

settings. Please refer to their documentation on multibyte text.

1.4.7. Definir um editor de texto predefinido

Debian vem com um número de editores diferentes. Nós

recomendamos instalar o pacote vim, como mencionado em cima.

Debian provides unified access to the system default editor via

command "/usr/bin/editor" so other programs (e.g., reportbug(1))

can invoke it. You can change it by the following.

$ sudo update-alternatives --config editor

A escolha de "/usr/bin/vim.basic" sobre "/usr/bin/vim.tiny" é

recomendação minha para novatos porque suporta destaque de

sintaxe.

Dica

Page 102: Referências Debian

Many programs use the environment variables "$EDITOR" or

"$VISUAL" to decide which editor to use (see Secção 1.3.5, “O

editor interno em MC” and Secção 9.5.11, “Personalizar o

programa a ser arrancado”). For the consistency on Debian

system, set these to "/usr/bin/editor". (Historically, "$EDITOR"

was "ed" and "$VISUAL" was "vi".)

1.4.8. Personalizar o vim

Você pode personalizar o comportamento do vim(1) em "~/.vimrc".

Por exemplo, tente o seguinte

" -------------------------------

" Local configuration

"

set nocompatible

set nopaste

set pastetoggle=<f2>

syn on

if $USER == "root"

set nomodeline

set noswapfile

else

set modeline

set swapfile

endif

" filler to avoid the line above being recognized as a modeline

" filler

Page 103: Referências Debian

" filler

1.4.9. Gravar as actividades da shell

The output of the shell command may roll off your screen and may

be lost forever. It is good practice to log shell activities

into the file for you to review them later. This kind of record

is essential when you perform any system administration tasks.

O método básico de gravar a actividade da shell é corrê-la sob

script(1).

Por exemplo, tente o seguinte

$ script

Script iniciado, ficheiro é typescript

Faz quaisquer comandos de shell sob script.

Carregue em Ctrl-D para terminar o script.

$ vim typescript

Veja Secção 9.2.3, “Gravar as actividades da shell de modo

limpo” .

1.4.10. Comandos Unix básicos

Let's learn basic Unix commands. Here I use "Unix" in its

Page 104: Referências Debian

generic sense. Any Unix clone OSs usually offer equivalent

commands. The Debian system is no exception. Do not worry if

some commands do not work as you wish now. If alias is used in

the shell, its corresponding command outputs are different.

These examples are not meant to be executed in this order.

Tente os comandos seguintes a partir da conta de utilizador

não-privilegiado.

Tabela 1.16. lista dos comandos Unix básicos

┌─────────────────┬────────────────────────────────────────────┐

comando descrição │ │ │

├─────────────────┼────────────────────────────────────────────┤

pwd mostra o nome do directório actual │ │ │

├─────────────────┼────────────────────────────────────────────┤

whoami mostra o nome do utilizador actual │ │ │

├─────────────────┼────────────────────────────────────────────┤

id mostra a identidade do utilizador actual │ │ │

(nome, uid, gid, e grupos associados) │ │ │

├─────────────────┼────────────────────────────────────────────┤

file <foo> mostra o tipo de ficheiro para o ficheiro " │ │ │

<foo>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

type -p mostra uma localização de ficheiro do │ │ │

Page 105: Referências Debian

<nome_do_comando> comando "<nome_do_comando>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

which , , │ │ │

<nome_do_comando> │ │ │

├─────────────────┼────────────────────────────────────────────┤

type mostra informação do comando " │ │ │

<nome_do_comando> <nome_do_comando>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

apropos mostra comandos relacionados com a " │ │ │

<palavra_chave> <palavra_chave>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

man -k , , │ │ │

<palavra_chave> │ │ │

├─────────────────┼────────────────────────────────────────────┤

whatis display one line explanation on command " │ │ │

<nome_do_comando> <commandname>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

man -a mostra explicação sobre o comando " │ │ │

<nome_do_comando> <nome_do_comando>" (o estilo Unix) │ │ │

├─────────────────┼────────────────────────────────────────────┤

info mostra uma explicação longa do comando " │ │ │

<nome_do_comando> <nome_do_comando>" (o estilo GNU) │ │ │

├─────────────────┼────────────────────────────────────────────┤

ls lista o conteúdo do directório (ficheiros e │ │ │

Page 106: Referências Debian

directórios não escondidos) │ │ │

├─────────────────┼────────────────────────────────────────────┤

ls -a lista o conteúdo do directório (todos os │ │ │

ficheiros e directórios) │ │ │

├─────────────────┼────────────────────────────────────────────┤

lista o conteúdo do directório (quase todos │ │ │

ls -A os ficheiros e directórios, isto é, salta o │ │ │

".." e ".") │ │ │

├─────────────────┼────────────────────────────────────────────┤

ls -la lista todo o conteúdo do directório com │ │ │

informação detalhada │ │ │

├─────────────────┼────────────────────────────────────────────┤

ls -lai lista todo o conteúdo do directório com │ │ │

número de inode e informação detalhada │ │ │

├─────────────────┼────────────────────────────────────────────┤

ls -d lista todos os directórios sob o directório │ │ │

actual │ │ │

├─────────────────┼────────────────────────────────────────────┤

tree mostra o conteúdo da árvore de ficheiros │ │ │

├─────────────────┼────────────────────────────────────────────┤

lsof <foo> lista o estado aberto do ficheiro "<foo>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

lsof -p <pid> lista ficheiros abertos pelo ID de processo:│ │ │

"<pid>" │ │ │

Page 107: Referências Debian

├─────────────────┼────────────────────────────────────────────┤

mkdir <foo> make a new directory "<foo>" in the current │ │ │

directory │ │ │

├─────────────────┼────────────────────────────────────────────┤

rmdir <foo> remove um directório "<foo>" no directório │ │ │

actual │ │ │

├─────────────────┼────────────────────────────────────────────┤

change directory to the directory "<foo>" in│ │ │

cd <foo> the current directory or in the directory │ │ │

listed in the variable "$CDPATH" │ │ │

├─────────────────┼────────────────────────────────────────────┤

cd / muda o directório para o directório raiz │ │ │

├─────────────────┼────────────────────────────────────────────┤

cd muda o directório para o directório home do │ │ │

utilizador actual │ │ │

├─────────────────┼────────────────────────────────────────────┤

cd /<foo> muda o directório para o directório de │ │ │

caminho absoluto "/<foo>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

cd .. muda o directório para o directório pai │ │ │

├─────────────────┼────────────────────────────────────────────┤

cd ~<foo> muda o directório para o directório home do │ │ │

utilizador "<foo>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

Page 108: Referências Debian

cd - muda o directório para o directório anterior│ │ │

├─────────────────┼────────────────────────────────────────────┤

</etc/motd pager mostra o conteúdo de "/etc/motd" usando o │ │ │

paginador predefinido │ │ │

├─────────────────┼────────────────────────────────────────────┤

touch <junkfile> cria um ficheiro vazio "<junkfile>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

cp <foo> <bar> copia um ficheiro "<foo>" existente para um │ │ │

novo ficheiro "<bar>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

rm <junkfile> remove um ficheiro "<junkfile>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

mv <foo> <bar> rename an existing file "<foo>" to a new │ │ │

name "<bar>" ("<bar>" must not exist) │ │ │

├─────────────────┼────────────────────────────────────────────┤

move an existing file "<foo>" to a new │ │ │

mv <foo> <bar> location "<bar>/<foo>" (the directory "<bar>│ │ │

" must exist) │ │ │

├─────────────────┼────────────────────────────────────────────┤

move an existing file "<foo>" to a new │ │ │

mv <foo> <bar>/ location with a new name "<bar>/<baz>" (the │ │ │

<baz> directory "<bar>" must exist but the │ │ │

directory "<bar>/<baz>" must not exist) │ │ │

├─────────────────┼────────────────────────────────────────────┤

Page 109: Referências Debian

make an existing file "<foo>" to be │ │ │

chmod 600 <foo> non-readable and non-writable by the other │ │ │

people (non-executable for all) │ │ │

├─────────────────┼────────────────────────────────────────────┤

make an existing file "<foo>" to be readable│ │ │

chmod 644 <foo> but non-writable by the other people │ │ │

(non-executable for all) │ │ │

├─────────────────┼────────────────────────────────────────────┤

make an existing file "<foo>" to be readable│ │ │

chmod 755 <foo> but non-writable by the other people │ │ │

(executable for all) │ │ │

├─────────────────┼────────────────────────────────────────────┤

find . -name find matching filenames using shell " │ │ │

<padrão> <pattern>" (slower) │ │ │

├─────────────────┼────────────────────────────────────────────┤

locate -d . find matching filenames using shell " │ │ │

<padrão> <pattern>" (quicker using regularly │ │ │

generated database) │ │ │

├─────────────────┼────────────────────────────────────────────┤

grep -e "<padrão> find a "<pattern>" in all files ending with │ │ │

" *.html ".html" in current directory and display │ │ │

them all │ │ │

├─────────────────┼────────────────────────────────────────────┤

top mostra informação de processos usando ecrã │ │ │

completo, carregue em "q" para sair │ │ │

Page 110: Referências Debian

├─────────────────┼────────────────────────────────────────────┤

ps aux | pager mostra informação dos processos a correr │ │ │

usando saída ao estilo BSD │ │ │

├─────────────────┼────────────────────────────────────────────┤

ps -ef | pager mostra informação dos processos a correr │ │ │

usando saída ao estilo Unix system-V │ │ │

├─────────────────┼────────────────────────────────────────────┤

ps aux | grep -e mostra todos os processos que correm "exim" │ │ │

"[e]xim4*" e "exim4" │ │ │

├─────────────────┼────────────────────────────────────────────┤

ps axf | pager mostra informação de todos os processos a │ │ │

correr com saída em arte de ACSII │ │ │

├─────────────────┼────────────────────────────────────────────┤

kill <1234> mata todos os processos identificados pelo │ │ │

ID de processo: "<1234>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

gzip <foo> descomprime "<foo>" para criar "<foo>.gz" │ │ │

usando a codificação Lempel-Ziv (LZ77) │ │ │

├─────────────────┼────────────────────────────────────────────┤

gunzip <foo>.gz descomprime "<foo>.gz" para criar "<foo>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

comprime "<foo>" para criar "<foo>.bz2" │ │ │

usando o algoritmo de compressão de texto │ │ │

bzip2 <foo> organizado em blocos Burrows-Wheeler, e │ │ │

Page 111: Referências Debian

codificação Huffman (melhor compressão que │ │ │

gzip) │ │ │

├─────────────────┼────────────────────────────────────────────┤

bunzip2 <foo>.bz2 descomprime "<foo>.bz2" para criar "<foo>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

comprime "<foo>" para criar "<foo>.xz" │ │ │

xz <foo> usando o algoritmo de cadeia │ │ │

Lempel–Ziv–Markov (melhor compressão que │ │ │

bzip2) │ │ │

├─────────────────┼────────────────────────────────────────────┤

unxz <foo>.xz descomprime "<foo>.xz" para criar "<foo>" │ │ │

├─────────────────┼────────────────────────────────────────────┤

tar -xvf extrai ficheiros do arquivo "<foo>.tar" │ │ │

<foo>.tar │ │ │

├─────────────────┼────────────────────────────────────────────┤

tar -xvzf extrai ficheiros do arquivo gzipado " │ │ │

<foo>.tar.gz <foo>.tar.gz" │ │ │

├─────────────────┼────────────────────────────────────────────┤

tar -xvjf extrai ficheiros do arquivo "<foo>.tar.bz2" │ │ │

<foo>.tar.bz2 │ │ │

├─────────────────┼────────────────────────────────────────────┤

tar -xvJf extrai ficheiros do arquivo "<foo>.tar.xz" │ │ │

<foo>.tar.xz │ │ │

├─────────────────┼────────────────────────────────────────────┤

Page 112: Referências Debian

tar -cvf arquiva o conteúdo da pasta "<bar>/" no │ │ │

<foo>.tar <bar>/ arquivo "<foo>.tar" │ │ │

├─────────────────┼────────────────────────────────────────────┤

tar -cvzf arquiva o conteúdo da pasta "<bar>/" no │ │ │

<foo>.tar.gz arquivo comprimido "<foo>.tar.gz" │ │ │

<bar>/ │ │ │

├─────────────────┼────────────────────────────────────────────┤

tar -cvjf arquiva o conteúdo da pasta "<bar>/" no │ │ │

<foo>.tar.bz2 arquivo "<foo>.tar.bz2" │ │ │

<bar>/ │ │ │

├─────────────────┼────────────────────────────────────────────┤

tar -cvJf arquiva o conteúdo da pasta "<bar>/" no │ │ │

<foo>.tar.xz arquivo "<foo>.tar.xz" │ │ │

<bar>/ │ │ │

├─────────────────┼────────────────────────────────────────────┤

zcat README.gz | mostra o conteúdo do "README.gz" comprimido │ │ │

pager usando o paginador predefinido │ │ │

├─────────────────┼────────────────────────────────────────────┤

zcat README.gz > cria o ficheiro "foo" com o conteúdo │ │ │

foo descomprimido de "README.gz" │ │ │

├─────────────────┼────────────────────────────────────────────┤

zcat README.gz >> acrescenta o conteúdo descomprimido de │ │ │

foo "README.gz" ao final do ficheiro "foo" (se │ │ │

ele não existir, é primeiro criado) │ │ │

└─────────────────┴────────────────────────────────────────────┘

Page 113: Referências Debian

Nota

Unix tem a tradição de esconder os nomes de ficheiros que

começam com ".". Eles são tradicionalmente ficheiros que contêm

informação de configuração e preferências do utilizador.

Nota

Para o comando cd, veja builtins(7).

Nota

O paginador predefinido da vastidão do sistema Debian é o more

(1), o qual não pode deslocar para trás. A instalar o pacote

less usando o comando "apt-get install less", o less(1) torna-se

o paginador predefinido e você pode deslocar para trás com as

teclas do cursor.

Nota

The "[" and "]" in the regular expression of the "ps aux | grep

-e "[e]xim4*"" command above enable grep to avoid matching

itself. The "4*" in the regular expression means 0 or more

repeats of character "4" thus enables grep to match both "exim"

and "exim4". Although "*" is used in the shell filename glob and

the regular expression, their meanings are different. Learn the

regular expression from grep(1).

Page 114: Referências Debian

Please traverse directories and peek into the system using the

above commands as training. If you have questions on any of

console commands, please make sure to read the manual page.

Por exemplo, tente o seguinte

$ man man

$ man bash

$ man builtins

$ man grep

$ man ls

The style of man pages may be a little hard to get used to,

because they are rather terse, particularly the older, very

traditional ones. But once you get used to it, you come to

appreciate their succinctness.

Please note that many Unix-like commands including ones from GNU

and BSD display brief help information if you invoke them in one

of the following ways (or without any arguments in some cases).

$ <nome_do_comando> --help

$ <nome_do_comando> -h

1.5. O simples comando de shell

Now you have some feel on how to use the Debian system. Let's

look deep into the mechanism of the command execution in the

Page 115: Referências Debian

Debian system. Here, I have simplified reality for the newbie.

See bash(1) for the exact explanation.

Um comando simples é uma sequência de componentes.

1. Variable assignments (optional)

2. Nome do comando

3. Argumentos (opcional)

4. Re-direcções (opcional: > , >> , < , << , etc.)

5. Control operator (optional: && , || , <newline> , ; , & , (

, ) )

1.5.1. Execução de comando e variável de ambiente

Values of some environment variables change the behavior of some

Unix commands.

Default values of environment variables are initially set by the

PAM system and then some of them may be reset by some

application programs.

The display manager such as gdm resets environment●

variables.

The shell in its start up codes resets environment variables●

in "~/bash_profile" and "~/.bashrc".

1.5.2. variável "$LANG"

The full locale value given to "$LANG" variable consists of 3

Page 116: Referências Debian

parts: "xx_YY.ZZZZ".

Tabela 1.17. 3 partes do valor locale

┌────────────┬────────────────────────────────────────────────┐

valor locale significado │ │ │

├────────────┼────────────────────────────────────────────────┤

xx ISO 639 language codes (lower case) such as "en"│ │ │

├────────────┼────────────────────────────────────────────────┤

YY ISO 3166 country codes (upper case) such as "US"│ │ │

├────────────┼────────────────────────────────────────────────┤

ZZZZ codificação, definir sempre para "UTF-8" │ │ │

└────────────┴────────────────────────────────────────────────┘

For language codes and country codes, see pertinent description

in the "info gettext".

For the codeset on the modern Debian system, you should always

set it to UTF-8 unless you specifically want to use the historic

one with good reason and background knowledge.

Para mais detalhes sobre configuração do locale, veja

Secção 8.3, “O locale”.

Nota

Page 117: Referências Debian

The "LANG=en_US" is not "LANG=C" nor "LANG=en_US.UTF-8". It is

"LANG=en_US.ISO-8859-1" (see Secção 8.3.1, “Bases de

codificação”).

Tabela 1.18. Lista de recomendações de locale

┌──────────────────────┬─────────────────────────────┐

recomendação de locale Linguagem (área) │ │ │

├──────────────────────┼─────────────────────────────┤

en_US.UTF-8 Inglês(EUA) │ │ │

├──────────────────────┼─────────────────────────────┤

en_GB.UTF-8 Inglês(Grã-Bretanha) │ │ │

├──────────────────────┼─────────────────────────────┤

fr_FR.UTF-8 Francês(França) │ │ │

├──────────────────────┼─────────────────────────────┤

de_DE.UTF-8 Alemão(Alemanha) │ │ │

├──────────────────────┼─────────────────────────────┤

it_IT.UTF-8 Italiano(Itália) │ │ │

├──────────────────────┼─────────────────────────────┤

es_ES.UTF-8 Espanhol(Espanha) │ │ │

├──────────────────────┼─────────────────────────────┤

ca_ES.UTF-8 Catalão(Espanha) │ │ │

├──────────────────────┼─────────────────────────────┤

sv_SE.UTF-8 Sueco(Suécia) │ │ │

├──────────────────────┼─────────────────────────────┤

pt_BR.UTF-8 Português(Brasil) │ │ │

├──────────────────────┼─────────────────────────────┤

ru_RU.UTF-8 Russo(Rússia) │ │ │

Page 118: Referências Debian

├──────────────────────┼─────────────────────────────┤

zh_CN.UTF-8 Chinês(Rep._Popular_da_China)│ │ │

├──────────────────────┼─────────────────────────────┤

zh_TW.UTF-8 Chinês(Taiwan_R.O.C.) │ │ │

├──────────────────────┼─────────────────────────────┤

ja_JP.UTF-8 Japonês(Japão) │ │ │

├──────────────────────┼─────────────────────────────┤

ko_KR.UTF-8 Coreano(República_da_Coreia) │ │ │

├──────────────────────┼─────────────────────────────┤

vi_VN.UTF-8 Vietnamita(Vietname) │ │ │

└──────────────────────┴─────────────────────────────┘

A execução de comando típica uma sequência de linha de shell

como o seguinte.

$ date

Sun Jun 3 10:27:39 JST 2007

$ LANG=fr_FR.UTF-8 date

dimanche 3 juin 2007, 10:27:33 (UTC+0900)

Aqui, o programa date(1) é executado com diferentes valores da

variável de ambiente "$LANG".

For the first command, "$LANG" is set to the system default●

locale value "en_US.UTF-8".

For the second command, "$LANG" is set to the French UTF-8●

locale value "fr_FR.UTF-8".

Page 119: Referências Debian

Most command executions usually do not have preceding

environment variable definition. For the above example, you can

alternatively execute as the following.

$ LANG=fr_FR.UTF-8

$ date

dimanche 3 juin 2007, 10:27:33 (UTC+0900)

As you can see here, the output of command is affected by the

environment variable to produce French output. If you want the

environment variable to be inherited to subprocesses (e.g., when

calling shell script), you need to export it instead by the

following.

$ export LANG

Dica

When filing a bug report, running and checking the command under

"LANG=en_US.UTF-8" is good idea if you use non-English

environment.

See locale(5) and locale(7) for "$LANG" and related environment

variables.

Nota

I recommend you to configure the system environment just by the

"$LANG" variable and to stay away from "$LC_*" variables unless

Page 120: Referências Debian

it is absolutely needed.

1.5.3. variável "$PATH"

When you type a command into the shell, the shell searches the

command in the list of directories contained in the "$PATH"

environment variable. The value of the "$PATH" environment

variable is also called the shell's search path.

In the default Debian installation, the "$PATH" environment

variable of user accounts may not include "/sbin" and "/usr/

sbin". For example, the ifconfig command needs to be issued with

full path as "/sbin/ifconfig". (Similar ip command is located in

"/bin".)

You can change the "$PATH" environment variable of Bash shell by

"~/.bash_profile" or "~/.bashrc" files.

1.5.4. variável "$HOME"

Many commands stores user specific configuration in the home

directory and changes their behavior by their contents. The home

directory is identified by the environment variable "$HOME".

Tabela 1.19. Lista de valores "$HOME"

┌───────────────────┬──────────────────────────────────────────┐

valor de "$HOME" situação de execução do programa │ │ │

Page 121: Referências Debian

├───────────────────┼──────────────────────────────────────────┤

/ programa executado pelo processo de init │ │ │

(daemon) │ │ │

├───────────────────┼──────────────────────────────────────────┤

/root programa executado a partir da shell de │ │ │

root normal │ │ │

├───────────────────┼──────────────────────────────────────────┤

/home/ programa executado a partir da shell de │ │ │

<utilizador_normal> utilizador normal │ │ │

├───────────────────┼──────────────────────────────────────────┤

/home/ program run from the normal user GUI │ │ │

<utilizador_normal> desktop menu │ │ │

├───────────────────┼──────────────────────────────────────────┤

/home/ program run as root with "sudo program" │ │ │

<utilizador_normal> │ │ │

├───────────────────┼──────────────────────────────────────────┤

/root program run as root with "sudo -H program"│ │ │

└───────────────────┴──────────────────────────────────────────┘

Dica

Shell expands "~/" to current user's home directory, i.e.,

"$HOME/". Shell expands "~foo/" to foo's home directory, i.e., "

/home/foo/".

Page 122: Referências Debian

1.5.5. Opções de linha de comandos

Some commands take arguments. Arguments starting with "-" or

"--" are called options and control the behavior of the command.

$ date

Mon Oct 27 23:02:09 CET 2003

$ date -R

Mon, 27 Oct 2003 23:02:40 +0100

Aqui o argumento de linha de comandos "-R" altera o

comportamento de date(1) para gerar uma string da data

compatível com RFC2822

1.5.6. Glob da shell

Often you want a command to work with a group of files without

typing all of them. The filename expansion pattern using the

shell glob, (sometimes referred as wildcards), facilitate this

need.

Tabela 1.20. Padrões glob da shell

┌───────────┬──────────────────────────────────────────────────┐

padrão glob descrição de regra de correspondência │ │ │

da shell │ │ │

├───────────┼──────────────────────────────────────────────────┤

Page 123: Referências Debian

* nome de ficheiro (segmento) não iniciado com "." │ │ │

├───────────┼──────────────────────────────────────────────────┤

.* nome de ficheiro (segmento) iniciado com "." │ │ │

├───────────┼──────────────────────────────────────────────────┤

? exactamente um caractere │ │ │

├───────────┼──────────────────────────────────────────────────┤

[…] exactamente um caractere com qualquer caractere │ │ │

envolvido em colchetes │ │ │

├───────────┼──────────────────────────────────────────────────┤

[a-z] exactamente um caractere com qualquer caractere │ │ │

entre "a" e "z" │ │ │

├───────────┼──────────────────────────────────────────────────┤

[^…] exactamente um caractere que não seja qualquer │ │ │

caractere envolvido em colchetes (excluindo "^") │ │ │

└───────────┴──────────────────────────────────────────────────┘

Por exemplo, tente o seguinte

$ mkdir junk; cd junk; touch 1.txt 2.txt 3.c 4.h .5.txt ..6.txt

$ echo *.txt

1.txt 2.txt

$ echo *

1.txt 2.txt 3.c 4.h

$ echo *.[hc]

Page 124: Referências Debian

3.c 4.h

$ echo .*

. .. .5.txt ..6.txt

$ echo .*[^.]*

.5.txt ..6.txt

$ echo [^1-3]*

4.h

$ cd ..; rm -rf junk

Veja glob(7).

Nota

Unlike normal filename expansion by the shell, the shell pattern

"*" tested in find(1) with "-name" test etc., matches the

initial "." of the filename. (New POSIX feature)

Nota

BASH can be tweaked to change its glob behavior with its shopt

builtin options such as "dotglob", "noglob", "nocaseglob",

"nullglob", "nocaseglob", "extglob", etc. See bash(1).

1.5.7. Valor de retorno do comando

Each command returns its exit status (variable: "$?") as the

return value.

Tabela 1.21. Códigos de saída do comando

Page 125: Referências Debian

┌─────────────────────┬────────────────────┬───────────────────┐

estado de saída do valor de retorno valor de retorno │ │ │ │

comando numérico lógico │ │ │ │

├─────────────────────┼────────────────────┼───────────────────┤

sucesso zero, 0 TRUE │ │ │ │

├─────────────────────┼────────────────────┼───────────────────┤

erro não-zero, -1 FALSE │ │ │ │

└─────────────────────┴────────────────────┴───────────────────┘

por exemplo, tente o seguinte.

$ [ 1 = 1 ] ; echo $?

0

$ [ 1 = 2 ] ; echo $?

1

Nota

Please note that, in the logical context for the shell, success

is treated as the logical TRUE which has 0 (zero) as its value.

This is somewhat non-intuitive and needs to be reminded here.

1.5.8. Sequências de comandos típicas e redireccionamento da

shell

Page 126: Referências Debian

Let's try to remember following shell command idioms typed in

one line as a part of shell command.

Tabela 1.22. Idiomas de comandos de shell

┌──────────┬───────────────────────────────────────────────────┐

idioma do descrição │ │ │

comando │ │ │

├──────────┼───────────────────────────────────────────────────┤

command & background execution of command in the subshell │ │ │

├──────────┼───────────────────────────────────────────────────┤

comando1 | pipe the standard output of command1 to the │ │ │

comando2 standard input of command2 (concurrent execution) │ │ │

├──────────┼───────────────────────────────────────────────────┤

comando1 pipe both standard output and standard error of │ │ │

2>&1 | command1 to the standard input of command2 ( │ │ │

comando2 concurrent execution) │ │ │

├──────────┼───────────────────────────────────────────────────┤

comando1 ; execute command1 and command2 sequentially │ │ │

comando2 │ │ │

├──────────┼───────────────────────────────────────────────────┤

comando1 & execute command1; if successful, execute command2 │ │ │

& comando2 sequentially (return success if both command1 and │ │ │

command2 are successful) │ │ │

├──────────┼───────────────────────────────────────────────────┤

Page 127: Referências Debian

comando1 | execute command1; if not successful, execute │ │ │

| comando2 command2 sequentially (return success if command1 │ │ │

or command2 are successful) │ │ │

├──────────┼───────────────────────────────────────────────────┤

comando > redirect standard output of command to a file foo │ │ │

foo (overwrite) │ │ │

├──────────┼───────────────────────────────────────────────────┤

command 2> redirect standard error of command to a file foo │ │ │

foo (overwrite) │ │ │

├──────────┼───────────────────────────────────────────────────┤

command >> redirect standard output of command to a file foo │ │ │

foo (append) │ │ │

├──────────┼───────────────────────────────────────────────────┤

command redirect standard error of command to a file foo │ │ │

2>> foo (append) │ │ │

├──────────┼───────────────────────────────────────────────────┤

command > redirect both standard output and standard error of│ │ │

foo 2>&1 command to a file "foo" │ │ │

├──────────┼───────────────────────────────────────────────────┤

comando < redirect standard input of command to a file foo │ │ │

foo │ │ │

├──────────┼───────────────────────────────────────────────────┤

command << redirect standard input of command to the following│ │ │

delimiter lines until "delimiter" is met (here document) │ │ │

Page 128: Referências Debian

├──────────┼───────────────────────────────────────────────────┤

command redirect standard input of command to the following│ │ │

<<- lines until "delimiter" is met (here document, the │ │ │

delimiter leading tab characters are stripped from input │ │ │

lines) │ │ │

└──────────┴───────────────────────────────────────────────────┘

The Debian system is a multi-tasking system. Background jobs

allow users to run multiple programs in a single shell. The

management of the background process involves the shell

builtins: jobs, fg, bg, and kill. Please read sections of bash

(1) under "SIGNALS", and "JOB CONTROL", and builtins(1).

Por exemplo, tente o seguinte

$ </etc/motd pager

$ pager </etc/motd

$ pager /etc/motd

$ cat /etc/motd | pager

Although all 4 examples of shell redirections display the same

thing, the last example runs an extra cat command and wastes

resources with no reason.

Page 129: Referências Debian

The shell allows you to open files using the exec builtin with

an arbitrary file descriptor.

$ echo Hello >foo

$ exec 3<foo 4>bar # abrir ficheiros

$ cat <&3 >&4 # redireccionar stdin para 3, stdout para 4

$ exec 3<&- 4>&- # fechar ficheiros

$ cat bar

Hello

Here, "n<&-" and "n>&-" mean to close the file descriptor "n".

The file descriptor 0-2 are predefined.

Tabela 1.23. Predefined file descriptors

┌───────────┬────────────────┬─────────────────────┐

dispositivo descrição descritor de ficheiro│ │ │ │

├───────────┼────────────────┼─────────────────────┤

stdin entrada standard 0 │ │ │ │

├───────────┼────────────────┼─────────────────────┤

stdout saída standard 1 │ │ │ │

├───────────┼────────────────┼─────────────────────┤

stderr erro standard 2 │ │ │ │

└───────────┴────────────────┴─────────────────────┘

1.5.9. Command alias

Page 130: Referências Debian

You can set an alias for the frequently used command.

Por exemplo, tente o seguinte

$ alias la='ls -la'

Now, "la" works as a short hand for "ls -la" which lists all

files in the long listing format.

You can list any existing aliases by alias (see bash(1) under

"SHELL BUILTIN COMMANDS").

$ alias

...

alias la='ls -la'

You can identity exact path or identity of the command by type

(see bash(1) under "SHELL BUILTIN COMMANDS").

Por exemplo, tente o seguinte

$ type ls

ls is hashed (/bin/ls)

$ type la

la is aliased to ls -la

$ type echo

echo is a shell builtin

$ type file

file is /usr/bin/file

Page 131: Referências Debian

Here ls was recently searched while "file" was not, thus "ls" is

"hashed", i.e., the shell has an internal record for the quick

access to the location of the "ls" command.

Dica

Veja Secção 9.2.7, “Comandos coloridos”.

1.6. Processamento de texto estilo Unix

In Unix-like work environment, text processing is done by piping

text through chains of standard text processing tools. This was

another crucial Unix innovation.

1.6.1. Ferramentas de texto de Unix

Existem algumas ferramentas standard de processamento de texto

que são muito usadas nos sistemas tipo Unix.

Nenhuma expressão regular é usada:●

cat(1) concatena ficheiros e escreve o conteúdo inteiro.○

tac(1) concatena ficheiros e escreve-os em reverso.○

cut(1) selecciona partes de linhas e escreve-as.○

head(1) escreve a parte inicial de ficheiros.○

tail(1) escreve a parte final de ficheiros.○

sort(1) organiza as linhas de ficheiros de texto.○

uniq(1) remove linhas duplicadas de um ficheiro○

Page 132: Referências Debian

organizado.

tr(1) traduz ou apaga caracteres.○

diff(1) compara ficheiros linha a linha.○

É usada uma expressão regular básica (BRE):●

grep(1) faz coincidir texto com padrões.○

ed(1) é um editor de linhas primitivo.○

sed(1) é um editor de fluxos.○

vim(1) é um editor de écran.○

emacs(1) é um editor de écran. (BRE de certo modo○

extensa)

É usada expressão regular extensa (ERE):●

egrep(1) faz coincidir texto com padrões.○

awk(1) faz processamento de texto simples.○

tcl(3tcl) pode fazer todo o processamento de texto○

concebível: re_syntax(3). Bastante usado com tk(3tk).

perl(1) pode fazer todo o processamento de texto○

concebível. perlre(1).

pcregrep(1) from the pcregrep package matches text with○

Perl Compatible Regular Expressions (PCRE) pattern.

python(1) com o módulo re pode fazer todo o○

processamento de texto concebível. Veja "/usr/share/doc/

python/html/index.html".

Se você não ter a certeza do que estes comandos fazem, por favor

use "man comando" para descobri-lo por si.

Nota

Page 133: Referências Debian

Sort order and range expression are locale dependent. If you

wish to obtain traditional behavior for a command, use C locale

instead of UTF-8 ones by prepnding command with "LANG=C" (see

Secção 1.5.2, “variável "$LANG"” and Secção 8.3, “O locale”).

Nota

Perl regular expressions (perlre(1)), Perl Compatible Regular

Expressions (PCRE), and Python regular expressions offered by

the re module have many common extensions to the normal ERE.

1.6.2. Expressões regulares

Regular expressions are used in many text processing tools. They

are analogous to the shell globs, but they are more complicated

and powerful.

The regular expression describes the matching pattern and is

made up of text characters and metacharacters.

The metacharacter is just a character with a special meaning.

There are 2 major styles, BRE and ERE, depending on the text

tools as described above.

Tabela 1.24. Meta-caracteres para BRE e ERE

┌─────────┬──────┬─────────────────────────────────────────────┐

Page 134: Referências Debian

BRE ERE descrição da expressão regular │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

\ . [ ] ^ \ . [ │ │ │ │

$ * ] ^ $ common metacharacters │ │ │ │

* │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

\+ \? \( │ │ │ │

\) \{ \} BRE only "\" escaped metacharacters │ │ │ │

\| │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

+ ? ( │ │ │ │

) { } ERE only non-"\" escaped metacharacters │ │ │ │

| │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

c c match non-metacharacter "c" │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

\c \c match a literal character "c" even if "c" is │ │ │ │

metacharacter by itself │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

. . match any character including newline │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

^ ^ posição no início de uma string │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

$ $ posição no fim de uma string │ │ │ │

Page 135: Referências Debian

├─────────┼──────┼─────────────────────────────────────────────┤

\< \< position at the beginning of a word │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

\> \> position at the end of a word │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

\[abc…\] [abc…] match any characters in "abc…" │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

\[^abc…\] [^ match any characters except in "abc…" │ │ │ │

abc…] │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

r* r* match zero or more regular expressions │ │ │ │

identified by "r" │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

r\+ r+ match one or more regular expressions │ │ │ │

identified by "r" │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

r\? r? match zero or one regular expressions │ │ │ │

identified by "r" │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

r1\|r2 r1|r2 match one of the regular expressions │ │ │ │

identified by "r1" or "r2" │ │ │ │

├─────────┼──────┼─────────────────────────────────────────────┤

\(r1\|r2 (r1| match one of the regular expressions │ │ │ │

\) r2) identified by "r1" or "r2" and treat it as a │ │ │ │

Page 136: Referências Debian

bracketed regular expression │ │ │ │

└─────────┴──────┴─────────────────────────────────────────────┘

The regular expression of emacs is basically BRE but has been

extended to treat "+"and "?" as the metacharacters as in ERE.

Thus, there are no needs to escape them with "\" in the regular

expression of emacs.

grep(1) pode ser usado para executar a pesquisa de texto usando

a expressão regular.

Por exemplo, tente o seguinte

$ egrep 'GNU.*LICENSE|Yoyodyne' /usr/share/common-licenses/GPL

GNU GENERAL PUBLIC LICENSE

GNU GENERAL PUBLIC LICENSE

Yoyodyne, Inc., hereby disclaims all copyright interest in the program

Dica

Veja Secção 9.2.7, “Comandos coloridos”.

1.6.3. Expressões de substituição

Para a expressão de substituição, alguns caracteres têm

significados especiais.

Page 137: Referências Debian

Tabela 1.25. A expressão de substituição

┌────────────────┬─────────────────────────────────────────────┐

expressão de descrição do texto para substituir a │ │ │

substituição expressão de substituição │ │ │

├────────────────┼─────────────────────────────────────────────┤

& what the regular expression matched (use \& │ │ │

in emacs) │ │ │

├────────────────┼─────────────────────────────────────────────┤

\n what the n-th bracketed regular expression │ │ │

matched ("n" being number) │ │ │

└────────────────┴─────────────────────────────────────────────┘

For Perl replacement string, "$n" is used instead of "\n" and "&

" has no special meaning.

Por exemplo, tente o seguinte

$ echo zzz1abc2efg3hij4 | \

sed -e 's/\(1[a-z]*\)[0-9]*\(.*\)$/=&=/'

zzz=1abc2efg3hij4=

$ echo zzz1abc2efg3hij4 | \

sed -e 's/\(1[a-z]*\)[0-9]*\(.*\)$/\2===\1/'

zzzefg3hij4===1abc

$ echo zzz1abc2efg3hij4 | \

perl -pe 's/(1[a-z]*)[0-9]*(.*)$/$2===$1/'

Page 138: Referências Debian

zzzefg3hij4===1abc

$ echo zzz1abc2efg3hij4 | \

perl -pe 's/(1[a-z]*)[0-9]*(.*)$/=&=/'

zzz=&=

Here please pay extra attention to the style of the bracketed

regular expression and how the matched strings are used in the

text replacement process on different tools.

These regular expressions can be used for cursor movements and

text replacement actions in some editors too.

The back slash "\" at the end of line in the shell commandline

escapes newline as a white space character and continues shell

command line input to the next line.

Por favor leia todos os manuais relacionados para aprender estes

comandos.

1.6.4. Substituição global com expressões regulares

The ed(1) command can replace all instances of "FROM_REGEX" with

"TO_TEXT" in "file".

$ ed file <<EOF

,s/FROM_REGEX/TO_TEXT/g

w

q

EOF

Page 139: Referências Debian

The sed(1) command can replace all instances of "FROM_REGEX"

with "TO_TEXT" in "file".

$ sed file 's/FROM_REGEX/TO_TEXT/g' | sponge file

Dica

The sponge(8) command is a non-standard Unix tool offered by the

moreutils package. This is quite useful when you wish to

overwrite original file.

The vim(1) command can replace all instances of "FROM_REGEX"

with "TO_TEXT" in "file" by using ex(1) commands.

$ vim '+%s/FROM_REGEX/TO_TEXT/gc' '+w' '+q' ficheiro

Dica

The "c" flag in the above ensures interactive confirmation for

each substitution.

Múltiplos ficheiros ("ficheiro1", "ficheiro2",e "ficheiro3")

podem ser processados com expressões regulares à semelhança com

vim(1) ou perl(1).

$ vim '+argdo %s/FROM_REGEX/TO_TEXT/ge|update' '+q' ficheiro1 ficheiro2 ficheiro3

Page 140: Referências Debian

Dica

The "e" flag in the above prevents the "No match" error from

breaking a mapping.

$ perl -i -p -e 's/FROM_REGEX/TO_TEXT/g;' ficheiro1 ficheiro2 ficheiro3

In the perl(1) example, "-i" is for in-place editing, "-p" is

for implicit loop over files.

Dica

Use of argument "-i.bak" instead of "-i" keeps each original

file by adding ".bak" to its filename. This makes recovery from

errors easier for complex substitutions.

Nota

ed(1) and vim(1) are BRE; perl(1) is ERE.

1.6.5. Extrair dados de tabela de ficheiro de texto

Let's consider a text file called "DPL" in which some pre-2004

Debian project leader's names and their initiation days are

listed in a space-separated format.

Ian Murdock August 1993

Bruce Perens April 1996

Ian Jackson January 1998

Page 141: Referências Debian

Wichert Akkerman January 1999

Ben Collins April 2001

Bdale Garbee April 2002

Martin Michlmayr March 2003

Dica

See "A Brief History of Debian" for the latest Debian leadership

history.

O awk é frequentemente usado para extrair dados deste tipo de

ficheiros.

Por exemplo, tente o seguinte

$ awk '{ print $3 }' <DPL # month started

August

April

January

January

April

April

March

$ awk '($1=="Ian") { print }' <DPL # DPL called Ian

Ian Murdock August 1993

Ian Jackson January 1998

$ awk '($2=="Perens") { print $3,$4 }' <DPL # When Perens started

April 1996

Page 142: Referências Debian

Shells such as Bash can be also used to parse this kind of file.

Por exemplo, tente o seguinte

$ while read first last month year; do

echo $month

done <DPL

... same output as the first Awk example

Here, the read builtin command uses characters in "$IFS"

(internal field separators) to split lines into words.

If you change "$IFS" to ":", you can parse "/etc/passwd" with

shell nicely.

$ oldIFS="$IFS" # guarda o valor antigo

$ IFS=':'

$ while read user password uid gid rest_of_line; do

if [ "$user" = "bozo" ]; then

echo "$user's ID is $uid"

fi

done < /etc/passwd

bozo's ID is 1000

$ IFS="$oldIFS" # restaura o valor antigo

(If Awk is used to do the equivalent, use "FS=':'" to set the

field separator.)

IFS is also used by the shell to split results of parameter

Page 143: Referências Debian

expansion, command substitution, and arithmetic expansion. These

do not occur within double or single quoted words. The default

value of IFS is <space>, <tab>, and <newline> combined.

Be careful about using this shell IFS tricks. Strange things may

happen, when shell interprets some parts of the script as its

input.

$ IFS=":," # use ":" and "," as IFS

$ echo IFS=$IFS, IFS="$IFS" # echo is a Bash builtin

IFS= , IFS=:,

$ date -R # just a command output

Sat, 23 Aug 2003 08:30:15 +0200

$ echo $(date -R) # sub shell --> input to main shell

Sat 23 Aug 2003 08 30 36 +0200

$ unset IFS # reset IFS to the default

$ echo $(date -R)

Sat, 23 Aug 2003 08:30:50 +0200

1.6.6. Script snippets for piping commands

The following scripts do nice things as a part of a pipe.

Tabela 1.26. List of script snippets for piping commands

┌─────────────────────┬────────────────────────────────────────┐

script snippet (type efeito do comando │ │ │

in one line) │ │ │

Page 144: Referências Debian

├─────────────────────┼────────────────────────────────────────┤

find /usr -print encontra todos os sob "/usr" │ │ │

├─────────────────────┼────────────────────────────────────────┤

seq 1 100 escreve 1 até 100 │ │ │

├─────────────────────┼────────────────────────────────────────┤

| xargs -n 1 run command repeatedly with each item │ │ │

<command> from pipe as its argument │ │ │

├─────────────────────┼────────────────────────────────────────┤

| xargs -n 1 echo split white-space-separated items from │ │ │

pipe into lines │ │ │

├─────────────────────┼────────────────────────────────────────┤

| xargs echo merge all lines from pipe into a line │ │ │

├─────────────────────┼────────────────────────────────────────┤

| grep -e extract lines from pipe containing │ │ │

<regex_pattern> <regex_pattern> │ │ │

├─────────────────────┼────────────────────────────────────────┤

| grep -v -e extract lines from pipe not containing │ │ │

<regex_pattern> <regex_pattern> │ │ │

├─────────────────────┼────────────────────────────────────────┤

| cut -d: -f3 - extract third field from pipe separated │ │ │

by ":" (passwd file etc.) │ │ │

├─────────────────────┼────────────────────────────────────────┤

| awk '{ print $3 }' extract third field from pipe separated │ │ │

by whitespaces │ │ │

Page 145: Referências Debian

├─────────────────────┼────────────────────────────────────────┤

| awk -F'\t' '{ print extract third field from pipe separated │ │ │

$3 }' by tab │ │ │

├─────────────────────┼────────────────────────────────────────┤

| col -bx remove backspace and expand tabs to │ │ │

spaces │ │ │

├─────────────────────┼────────────────────────────────────────┤

| expand - expande separadores │ │ │

├─────────────────────┼────────────────────────────────────────┤

| sort| uniq organiza e remove duplicados │ │ │

├─────────────────────┼────────────────────────────────────────┤

| tr 'A-Z' 'a-z' converte maiúsculas para minúsculas │ │ │

├─────────────────────┼────────────────────────────────────────┤

| tr -d '\n' concatena linhas em uma linha │ │ │

├─────────────────────┼────────────────────────────────────────┤

| tr -d '\r' remove CR │ │ │

├─────────────────────┼────────────────────────────────────────┤

| sed 's/^/# /' adiciona "#" ao inicio de cada linha │ │ │

├─────────────────────┼────────────────────────────────────────┤

| sed 's/\.ext//g' remove ".ext" │ │ │

├─────────────────────┼────────────────────────────────────────┤

| sed -n -e 2p escreve a segunda linha │ │ │

├─────────────────────┼────────────────────────────────────────┤

Page 146: Referências Debian

| head -n 2 - escreve as primeiras duas linhas │ │ │

├─────────────────────┼────────────────────────────────────────┤

| tail -n 2 - escreve as últimas duas linhas │ │ │

└─────────────────────┴────────────────────────────────────────┘

One-line shell script can loop over many files using find(1) and

xargs(1) to perform quite complicated tasks. See Secção 10.1.5,

“Idiomas para a selecção de ficheiros” and Secção 9.5.9,

“Repeating a command looping over files”.

Quando a utilização dos modos interactivos da shell se torna

muito complicada, por favor considere escrever um script de

shell (veja Secção 12.1, “O script shell”).

Capítulo 2. Gestão de pacotes Debian

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

Page 147: Referências Debian

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.

apt-get(8) para todas as operações de linha de comandos,●

incluindo a instalação e remoção de pacotes, e os

dist-upgrades.

aptitude(8) para uma interface de texto interactiva para●

gerir os pacotes instalados e procurar os pacotes

disponíveis.

update-manager(8) para manter o seu sistema actualizado se●

você estiver a correr o ambiente de trabalho GNOME

predefinido.

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

┌────────────────────┬───────┬───────┬─────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

Advanced Packaging Tool │ │ │ │ │

(APT), front-end for dpkg│ │ │ │ │

Page 148: Referências Debian

V:90, providing "http", "ftp", │ │ │ │ │

apt * I:99 5600 and "file" archive access│ │ │ │ │

methods (apt-get/ │ │ │ │ │

apt-cache commands │ │ │ │ │

included) │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

V:25, Gestor de pacotes baseado│ │ │ │ │

aptitude * I:98 11916 em terminal interactivo │ │ │ │ │

com aptitude(8) │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

Aplicação do GNOME que │ │ │ │ │

update-manager-gnome V:7, 1221 gere actualizações de │ │ │ │ │

* I:10 software com o │ │ │ │ │

update-manager(8) │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

ferramenta para │ │ │ │ │

V:5, seleccionar tarefas para │ │ │ │ │

tasksel * I:93 904 instalação no sistema │ │ │ │ │

Debian (frontend para o │ │ │ │ │

APT) │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

pacote de melhoramento │ │ │ │ │

unattended-upgrades V:4, para o APT para activar a│ │ │ │ │

* I:31 280 instalação automática de │ │ │ │ │

actualizações de │ │ │ │ │

segurança │ │ │ │ │

Page 149: Referências Debian

├────────────────────┼───────┼───────┼─────────────────────────┤

gestor de pacotes baseado│ │ │ │ │

V:2, em terminal (o standard │ │ │ │ │

dselect * I:30 2404 anterior, frontend para o│ │ │ │ │

APT e outros métodos de │ │ │ │ │

acesso antigos) │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

dpkg * V:92, 6804 sistema de gestão de │ │ │ │ │

I:99 pacotes para Debian │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

V:13, gestor de pacotes gráfico│ │ │ │ │

synaptic * I:40 6464 (frontend do GNOME para o│ │ │ │ │

APT) │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

Programas utilitários do │ │ │ │ │

apt-utils * V:51, 516 APT: apt-extracttemplates│ │ │ │ │

I:99 (1), apt-ftparchive(1), e│ │ │ │ │

apt-sortpkgs(1) │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

V:11, ferramenta de notificação│ │ │ │ │

apt-listchanges * I:17 280 do histórico de │ │ │ │ │

alterações do pacote │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

apt-listbugs * V:1.4, 508 lista bugs críticos antes│ │ │ │ │

I:2 de cada instalação do APT│ │ │ │ │

Page 150: Referências Debian

├────────────────────┼───────┼───────┼─────────────────────────┤

Utilitário de busca de │ │ │ │ │

apt-file * V:2, 188 pacotes do APT - │ │ │ │ │

I:9 interface de linha de │ │ │ │ │

comandos │ │ │ │ │

├────────────────────┼───────┼───────┼─────────────────────────┤

apt-rdepends * V:0.13, 92 lista dependências de │ │ │ │ │

I:0.9 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

Page 151: Referências Debian

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

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".

Page 152: Referências Debian

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.

Page 153: Referências Debian

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

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

Page 154: Referências Debian

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

Page 155: Referências Debian

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.●

Page 156: Referências 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

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 objectivo │ │ │ │

código) │ │ │ │

├────────────────────┼───────────────────────┼─────────────────┤

Page 157: Referências Debian

http:// lançamento │ │ │ │

ftp.XX.debian.org/ stable (squeeze) (squeeze) stable │ │ │ │

debian/ │ │ │ │

├────────────────────┼───────────────────────┼─────────────────┤

http:// lançamento │ │ │ │

ftp.XX.debian.org/ testing (wheezy) (wheezy) testing │ │ │ │

debian/ │ │ │ │

├────────────────────┼───────────────────────┼─────────────────┤

http:// lançamento (sid) │ │ │ │

ftp.XX.debian.org/ unstable (sid) unstable │ │ │ │

debian/ │ │ │ │

├────────────────────┼───────────────────────┼─────────────────┤

http:// pré-lançamento │ │ │ │

ftp.XX.debian.org/ experimental experimental │ │ │ │

debian/ (opcional, apenas│ │ │ │

para programador)│ │ │ │

├────────────────────┼───────────────────────┼─────────────────┤

Actualizações │ │ │ │

http:// para o próximo │ │ │ │

ftp.XX.debian.org/ stable-proposed-updates lançamento de │ │ │ │

debian/ ponto estável │ │ │ │

(opcional) │ │ │ │

├────────────────────┼───────────────────────┼─────────────────┤

actualizações de │ │ │ │

http:// stable/updates segurança para o │ │ │ │

security.debian.org/ lançamento stable│ │ │ │

Page 158: Referências Debian

(importante) │ │ │ │

├────────────────────┼───────────────────────┼─────────────────┤

actualizações de │ │ │ │

http:// segurança para o │ │ │ │

security.debian.org/ testing/updates lançamento │ │ │ │

testing │ │ │ │

(importante) │ │ │ │

├────────────────────┼───────────────────────┼─────────────────┤

compatible │ │ │ │

http:// updates for spam │ │ │ │

ftp.XX.debian.org/ squeeze-updates filter, IM │ │ │ │

debian/ clients, etc. for│ │ │ │

squeeze │ │ │ │

├────────────────────┼───────────────────────┼─────────────────┤

http:// newer backported │ │ │ │

backports.debian.org squeeze-backports packages for │ │ │ │

/debian-backports/ squeeze │ │ │ │

(optional) │ │ │ │

└────────────────────┴───────────────────────┴─────────────────┘

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.

Page 159: Referências Debian

If you really need the latest version of some programs under

stable release, please use packages from squeeze-updates and

http://backports.debian.org (see Secção 2.7.4, “Updates and

Backports”) services. These services must be used with extra

care.

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

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

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

Page 160: Referências Debian

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 critério do componente do pacote │ │ │ │

pacotes │ │ │ │

├────────┼─────────────┼───────────────────────────────────────┤

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.

Page 161: Referências Debian

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 nome de código nome de código = nome de │ │ │ │ │

lançamento = squeeze wheezy código = sid│ │ │ │ │

squeeze │ │ │ │ │

├────────────────┼───────────────┼────────────────┼────────────┤

após o nome de código nome de código = nome de │ │ │ │ │

lançamento = wheezy wheezy+1 código = sid│ │ │ │ │

wheezy │ │ │ │ │

└────────────────┴───────────────┴────────────────┴────────────┘

A história dos nomes de código está descrita em Debian FAQ:

Page 162: Referências Debian

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

Page 163: Referências Debian

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

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

Page 164: Referências Debian

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

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.

"Secções"●

"Prioridades"●

"Sistema base"●

"Pacotes essenciais"●

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

Page 165: Referências Debian

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"●

Page 166: Referências Debian

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

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"):●

Page 167: Referências Debian

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

Page 168: Referências Debian

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.

Page 169: Referências Debian

$ 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 sensible-browser "http:// │ │ │

acompanhamento de bugs Debian bugs.debian.org/" │ │ │

(BTS) │ │ │

├────────────────────────────────┼─────────────────────────────┤

O relatório de bug de um nome de sensible-browser "http:// │ │ │

pacote conhecido bugs.debian.org/ │ │ │

<nome_do_pacote>" │ │ │

├────────────────────────────────┼─────────────────────────────┤

O relatório de bug de um número sensible-browser "http:// │ │ │

Page 170: Referências Debian

de bug conhecido 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

Page 171: Referências Debian

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.

Page 172: Referências Debian

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

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).

┌────────────┬────────────┬────────────────────────────────────┐

Page 173: Referências Debian

sintaxe do sintaxe do │ │ │ │

aptitude apt-get/ descrição │ │ │ │

apt-cache │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude apt-get actualiza os metadados do arquivo de│ │ │ │

update update pacotes │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude apt-get instala a versão candidata do pacote│ │ │ │

install foo install foo "foo" com as suas dependências │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude apt-get instala as versões candidatas dos │ │ │ │

safe-upgrade upgrade pacotes instalados sem remover │ │ │ │

quaisquer outros pacotes │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude apt-get instala as versões candidatas dos │ │ │ │

full-upgrade dist-upgrade pacotes instalados removendo outros │ │ │ │

<package> pacotes caso necessário │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude apt-get remove o pacote "foo" deixando os │ │ │ │

remove foo remove foo seus ficheiros de configuração │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

N/D apt-get remove os pacote auto-instalados que│ │ │ │

autoremove já não são necessários │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude apt-get purga o pacote "foo" com os seus │ │ │ │

Page 174: Referências Debian

purge foo purge foo ficheiros de configuração │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude apt-get limpa completamente o repositório │ │ │ │

clean clean local de ficheiros de pacotes │ │ │ │

obtidos │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude apt-get clear out the local repository of │ │ │ │

autoclean autoclean retrieved package files for outdated│ │ │ │

packages │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude apt-cache mostra informação detalhada acerca │ │ │ │

show foo show do pacote "foo" │ │ │ │

<package> │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude apt-cache │ │ │ │

search search search packages which match <regex> │ │ │ │

<regex> <regex> │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude why explain the reason why <regex> │ │ │ │

<regex> N/D matching packages should be │ │ │ │

installed │ │ │ │

├────────────┼────────────┼────────────────────────────────────┤

aptitude explain the reason why <regex> │ │ │ │

why-not N/D matching packages can not be │ │ │ │

<regex> installed │ │ │ │

Page 175: Referências Debian

└────────────┴────────────┴────────────────────────────────────┘

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)

Page 176: Referências Debian

┌───────────┬──────────────────────────────────────────────────┐

opção de descrição │ │ │

comando │ │ │

├───────────┼──────────────────────────────────────────────────┤

-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

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

Page 177: Referências Debian

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

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

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

Page 178: Referências Debian

┌──────────────────────┬───────────────────────────────────────┐

tecla tecla de atalho │ │ │

├──────────────────────┼───────────────────────────────────────┤

F10 ou Ctrl-t menu │ │ │

├──────────────────────┼───────────────────────────────────────┤

? display help for keystroke (more │ │ │

complete listing) │ │ │

├──────────────────────┼───────────────────────────────────────┤

F10 → Ajuda → Manual mostra o Manual do Utilizador │ │ │

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 │ │ │

Page 179: Referências Debian

├──────────────────────┼───────────────────────────────────────┤

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 │ │ │

Page 180: Referências Debian

└──────────────────────┴───────────────────────────────────────┘

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

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)●

Page 181: Referências Debian

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

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”).

Estão disponíveis vários tipos de vistas de pacotes sob o menu

"Vistas".

Tabela 2.9. Lista de vistas para o aptitude

┌─────────────┬──────────┬─────────────────────────────────────┐

vista estado descrição da vista │ │ │ │

├─────────────┼──────────┼─────────────────────────────────────┤

Vista de veja Tabela 2.10, “A categorização │ │ │ │

Pacote Bom das vista de pacotes standard” │ │ │ │

(predefinição) │ │ │ │

├─────────────┼──────────┼─────────────────────────────────────┤

Page 182: Referências Debian

lista pacotes que são recomendados │ │ │ │

Auditoria de Bom por alguns pacotes instalados mas │ │ │ │

Recomendações ainda não estão listados como │ │ │ │

instalados │ │ │ │

├─────────────┼──────────┼─────────────────────────────────────┤

Lista de Bom lista pacotes sem categorização (para│ │ │ │

Pacotes Lisa usar com expressões regulares) │ │ │ │

├─────────────┼──────────┼─────────────────────────────────────┤

Explorador de Muito list packages categorized according │ │ │ │

Debtags utilizável to their debtags entries │ │ │ │

├─────────────┼──────────┼─────────────────────────────────────┤

Explorador lista pacotes categorizados de acordo│ │ │ │

por Obsoleto com a sua categoria (use o Explorador│ │ │ │

Categorias de Debtags, em vez disto) │ │ │ │

└─────────────┴──────────┴─────────────────────────────────────┘

Nota

Por favor ajude-nos a melhorar a etiquetagem de pacotes com

debtags!

A "Vista de Pacotes standard categoriza os pacotes de certo modo

como o dselect com algumas funcionalidades extra.

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

Page 183: Referências Debian

┌─────────────────────┬────────────────────────────────────────┐

categoria descrição da vista │ │ │

├─────────────────────┼────────────────────────────────────────┤

Pacotes Actualizáveis lista pacotes organizados como secção → │ │ │

área → pacote │ │ │

├─────────────────────┼────────────────────────────────────────┤

Pacotes Novos , , │ │ │

├─────────────────────┼────────────────────────────────────────┤

Pacotes Instalados , , │ │ │

├─────────────────────┼────────────────────────────────────────┤

Pacotes Não , , │ │ │

Instalados │ │ │

├─────────────────────┼────────────────────────────────────────┤

Pacotes Obsoletos ou , , │ │ │

Criados Localmente │ │ │

├─────────────────────┼────────────────────────────────────────┤

Pacotes Virtuais lista pacotes com a mesma função │ │ │

├─────────────────────┼────────────────────────────────────────┤

Tarefas lista pacotes com diferentes funções │ │ │

geralmente necessárias para uma tarefa │ │ │

└─────────────────────┴────────────────────────────────────────┘

Dica

Page 184: Referências Debian

A vista Tarefas pode ser usada para escolher pacotes para a sua

tarefa.

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

O aptitude oferece várias opções para você procurar pacotes

usando a sua fórmula de expressões regulares.

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

"/" para procurar um pacote correspondente○

"\" para procurar um pacote correspondente voltando para○

trás

"n" para procurar o próximo○

"N" para procurar o próximo (andando para trás)○

Dica

The string for <package_name> is treated as the exact string

Page 185: Referências Debian

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 fórmula da expressão regular │ │ │

extensa │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com o ~n<regex_name> │ │ │

nome do pacote │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com a ~d<regex_description> │ │ │

descrição │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com ~t<regex_task> │ │ │

nome da tarefa │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com ~G<regex_debtag> │ │ │

Page 186: Referências Debian

debtag │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com o ~m<regex_maintainer> │ │ │

maintainer │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com ~s<regex_section> │ │ │

secção do pacote │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com ~V<regex_version> │ │ │

versão do pacote │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com ~A{sarge,etch,sid} │ │ │

arquivo │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com ~O{debian,…} │ │ │

origem │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

prioridade da ~p{extra,important,optional,required,standard} │ │ │

correspondência │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com ~E │ │ │

pacotes essenciais │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com ~v │ │ │

Page 187: Referências Debian

pacotes virtuais │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com ~N │ │ │

pacotes novos │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com ~a │ │ │

acções pendentes {install,upgrade,downgrade,remove,purge,hold,keep}│ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com os ~i │ │ │

pacotes instalados │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

pacotes instalados │ │ │

com marca A (pacote ~M │ │ │

instalado │ │ │

automaticamente) │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

pacotes instalados │ │ │

sem a marca A ~i!~M │ │ │

(pacote │ │ │

seleccionado pelo │ │ │

administrador) │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

Page 188: Referências Debian

pacotes instalados ~U │ │ │

e com actualizações │ │ │

disponíveis │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

pacotes removidos ~c │ │ │

mas não purgados │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

pacotes removidos, ~g │ │ │

purgados ou que │ │ │

podem-ser-removidos │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

pacotes com ~b │ │ │

relações quebradas │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

pacotes com │ │ │

dependências/ ~B<type> │ │ │

pré-dependências/ │ │ │

conflitos quebrados │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

match packages from │ │ │

which relation ~D[<type>:]<term> │ │ │

<type> is defined │ │ │

Page 189: Referências Debian

to <term> package │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

match packages from │ │ │

which broken │ │ │

relation <type> is ~DB[<type>:]<term> │ │ │

defined to <term> │ │ │

package │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

match packages to │ │ │

which the <term> ~R[<type>:]<term> │ │ │

package defines │ │ │

relation <type> │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

match packages to │ │ │

which the <term> │ │ │

package defines ~RB[<type>:]<term> │ │ │

broken relation │ │ │

<type> │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

pacotes com os │ │ │

quais alguns ~R~i │ │ │

pacotes instalados │ │ │

dependem │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

Page 190: Referências Debian

pacotes com os │ │ │

quais nenhum outro !~R~i │ │ │

pacote instalado │ │ │

depende │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

pacotes com os │ │ │

quais alguns ~R~i|~Rrecommends:~i │ │ │

pacotes instalados │ │ │

dependem ou │ │ │

recomendam │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde o │ │ │

pacote <term> com a ~S filter <term> │ │ │

versão filtrada │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

corresponde com │ │ │

todos os pacotes ~T │ │ │

(true) │ │ │

├───────────────────┼──────────────────────────────────────────────────┤

não corresponde com │ │ │

nenhum pacote ~F │ │ │

(false) │ │ │

└───────────────────┴──────────────────────────────────────────────────┘

Page 191: Referências Debian

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).

A relação <type> é uma de (dependências, pré-dependências,●

recomendações, sugestões, conflitos, substituições,

fornecimentos).

O tipo de relação predefinido é "depends".●

Dica

Quando <regex_pattern> é uma string nula, coloca "~T"

imediatamente após o comando.

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

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

Page 192: Referências Debian

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

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 │ │ │

├──────────────┼───────────────────────────────────────────────┤

Page 193: Referências Debian

/var/log/ Log da actividade de nível do dpkg para as │ │ │

dpkg.log actividades de todos os pacotes │ │ │

├──────────────┼───────────────────────────────────────────────┤

/var/log/apt/ Log da actividade genérica do APT │ │ │

term.log │ │ │

├──────────────┼───────────────────────────────────────────────┤

/var/log/ Log da actividade de comandos do aptitude │ │ │

aptitude │ │ │

└──────────────┴───────────────────────────────────────────────┘

Na realidade, não é muito fácil obter uma compreensão

significativa rapidamente a partir destes logs. Veja

Secção 9.2.10, “Gravar alterações em ficheiros de configuração”

para um modo mais fácil.

2.3. Exemplos de operações do aptitude

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

2.3.1. Listagem de pacotes com correspondência por expressão

regular nos nomes de pacotes

O seguinte comando lista pacotes com o regex a condizer com

nomes de pacotes.

$ aptitude search '~n(pam|nss).*ldap'

Page 194: Referências Debian

p libnss-ldap - NSS module for using LDAP as a naming service

p libpam-ldap - Pluggable Authentication Module allowing LDAP interfaces

Isto dá muito jeito para para encontrar o nome exacto de um

pacote.

2.3.2. Explorar com a correspondência de expressão regular

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'

Se você acha que os pacotes listados estão OK para serem

purgados, execute o seguinte comando.

# aptitude purge '~c'

Você pode querer fazer semelhante no modo interactivo para um

controle mais preciso.

Page 195: Referências Debian

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.

Esta técnica é muito jeitosa e funciona com muitas outras teclas

de comando.

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

Page 196: Referências Debian

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

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

Page 197: Referências Debian

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.

Page 198: Referências Debian

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: oldstable → stable → testing →

unstable.

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

It is not wise to skip major Debian release when upgrading

between stable releases.

Page 199: Referências Debian

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 lista o estado de um pacote │ │ │

<padrão_do_nome_de_pacote> instalado para o relatório de bug│ │ │

├────────────────────────────┼─────────────────────────────────┤

dpkg -L <nome_do_pacote> lista o conteúdo de um pacote │ │ │

instalado │ │ │

Page 200: Referências Debian

├────────────────────────────┼─────────────────────────────────┤

dpkg -L <nome_do_pacote> | lista os manuais para um pacote │ │ │

egrep '/usr/share/man/man.* instalado │ │ │

/.+' │ │ │

├────────────────────────────┼─────────────────────────────────┤

dpkg -S lista os pacotes instalados que │ │ │

<padrão_do_nome_de_ficheiro> condizem com o nome de ficheiro │ │ │

├────────────────────────────┼─────────────────────────────────┤

apt-file search lista pacotes no arquivo que │ │ │

<padrão_do_nome_de_ficheiro> condizem com o nome de ficheiro │ │ │

├────────────────────────────┼─────────────────────────────────┤

apt-file list lista os conteúdos dos pacotes no│ │ │

<padrão_do_nome_de_pacote> arquivo que condizem │ │ │

├────────────────────────────┼─────────────────────────────────┤

dpkg-reconfigure reconfigura o pacote exacto │ │ │

<nome_do_pacote> │ │ │

├────────────────────────────┼─────────────────────────────────┤

dpkg-reconfigure -p=low reconfigura o pacote exacto com │ │ │

<nome_do_pacote> as questões mais detalhadas │ │ │

├────────────────────────────┼─────────────────────────────────┤

configure-debian reconfigura pacotes a partir do │ │ │

menu de écran completo │ │ │

├────────────────────────────┼─────────────────────────────────┤

dpkg --audit faz auditoria ao sistema por │ │ │

Page 201: Referências Debian

pacotes parcialmente instalados │ │ │

├────────────────────────────┼─────────────────────────────────┤

dpkg --configure -a configura todos os pacotes │ │ │

parcialmente instalados │ │ │

├────────────────────────────┼─────────────────────────────────┤

apt-cache policy mostra a versão disponível, a │ │ │

<nome_do_pacote_binário> prioridade e informação de │ │ │

arquivo de um pacote binário │ │ │

├────────────────────────────┼─────────────────────────────────┤

apt-cache madison mostra a versão disponível e │ │ │

<nome_do_pacote> informação de arquivo de um │ │ │

pacote │ │ │

├────────────────────────────┼─────────────────────────────────┤

apt-cache showsrc mostra informação do pacote fonte│ │ │

<nome_do_pacote_binário> de um pacote binário │ │ │

├────────────────────────────┼─────────────────────────────────┤

apt-get build-dep instala os pacote necessários │ │ │

<nome_do_pacote> para compilar pacote │ │ │

├────────────────────────────┼─────────────────────────────────┤

apt-get source descarrega uma fonte (do arquivo │ │ │

<nome_do_pacote> standard) │ │ │

├────────────────────────────┼─────────────────────────────────┤

dget <URL para ficheiro dsc> descarrega um pacote fonte (de │ │ │

outro arquivo) │ │ │

Page 202: Referências Debian

├────────────────────────────┼─────────────────────────────────┤

dpkg-source -x constrói uma árvore fonte a │ │ │

<nome_do_pacote>_<versão>- partir de um conjunto de pacotes │ │ │

<versão_debian>.dsc fonte ("*.orig.tar.gz" e │ │ │

"*.debian.tar.gz"/"*.diff.gz") │ │ │

├────────────────────────────┼─────────────────────────────────┤

debuild binary compila pacote(s) a partir de uma│ │ │

árvore fonte local │ │ │

├────────────────────────────┼─────────────────────────────────┤

compila um pacote de kernel a │ │ │

make-kpkg imagem_de_kernel partir de uma árvore fonte de │ │ │

kernel │ │ │

├────────────────────────────┼─────────────────────────────────┤

make-kpkg --initrd compila um pacote de kernel a │ │ │

imagem_de_kernel partir de uma árvore fonte de │ │ │

kernel com initramfs activa │ │ │

├────────────────────────────┼─────────────────────────────────┤

dpkg -i <nome_de_pacote> instala um pacote local no │ │ │

<versão>-<versão_debian> sistema │ │ │

<arquitectura>.deb │ │ │

├────────────────────────────┼─────────────────────────────────┤

debi <nome_de_pacote> instala pacote(s) locais no │ │ │

<versão>-<versão_debian> sistema │ │ │

<arquitectura>.dsc │ │ │

├────────────────────────────┼─────────────────────────────────┤

Page 203: Referências Debian

dpkg --get-selections '*' > guarda a informação de estado de │ │ │

selection.txt selecção a nível de pacotes do │ │ │

dpkg │ │ │

├────────────────────────────┼─────────────────────────────────┤

dpkg --set-selections define a informação de estado de │ │ │

<selection.txt selecção a nível de pacotes do │ │ │

dpkg │ │ │

├────────────────────────────┼─────────────────────────────────┤

set dpkg level package selection │ │ │

echo <package_name> hold | state for a package to hold │ │ │

dpkg --set-selections (equivalent to "aptitude hold │ │ │

<package_name>") │ │ │

└────────────────────────────┴─────────────────────────────────┘

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●

Page 204: Referências Debian

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/

Page 205: Referências Debian

dpkg/info/*.md5sums" com debsums(1). Veja Secção 10.4.5, “O

sumário MD5” para saber como o MD5sum funciona.

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.

Page 206: Referências Debian

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

Page 207: Referências Debian

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│ │ │ │

├──────────────┼─────────────────────┼─────────────────────────┤

ficheiro de assinatura │ │ │ │

Release.gpg topo da distribuição para o ficheiro "Release"│ │ │ │

assinado com a chave do │ │ │ │

arquivo │ │ │ │

├──────────────┼─────────────────────┼─────────────────────────┤

lista de todos os │ │ │ │

Contents- topo da distribuição ficheiros para todos os │ │ │ │

<architecture> pacotes no arquivo │ │ │ │

pertinente │ │ │ │

├──────────────┼─────────────────────┼─────────────────────────┤

topo de cada descrição do arquivo │ │ │ │

Release combinação de usada para a regra do │ │ │ │

distribuição/área/ apt_preferences(5) │ │ │ │

arquitectura │ │ │ │

├──────────────┼─────────────────────┼─────────────────────────┤

Page 208: Referências Debian

topo de cada debian/control │ │ │ │

Packages combinação de concatenado para pacotes │ │ │ │

distribuição/área/ binários │ │ │ │

arquitectura-binário │ │ │ │

├──────────────┼─────────────────────┼─────────────────────────┤

topo de cada debian/control │ │ │ │

Sources combinação de concatenado para pacotes │ │ │ │

distribuição/área/ fonte │ │ │ │

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

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

Page 209: Referências 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

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";

Page 210: Referências Debian

automatically by installing the keyring with the latest○

base-files package, or

manually by gpg or apt-key tool with the latest public○

archive key posted on the ftp-master.debian.org .

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

The archive level "Release" files are used for the rule of

apt_preferences(5).

Page 211: Referências Debian

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

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, 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

Page 212: Referências 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)

Page 213: Referências Debian

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.

Page 214: Referências Debian

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 <nome_de_pacote>_<epoch>: │ │ │

deb) <versão_upstream>-<versão.debian>- │ │ │

<arquitectura>.deb │ │ │

├────────────────────────┼─────────────────────────────────────┤

O pacote binário (a.k.a <nome_de_pacote>_<epoch>: │ │ │

Page 215: Referências Debian

udeb) <versão_upstream>-<versão.debian>- │ │ │

<arquitectura>.udeb │ │ │

├────────────────────────┼─────────────────────────────────────┤

O pacote fonte (fonte da <nome_de_pacote>_<epoch>: │ │ │

origem) <versão_upstream>- │ │ │

<versão.debian>.orig.tar.gz │ │ │

├────────────────────────┼─────────────────────────────────────┤

O pacote fonte 1.0 <nome_de_pacote>_<epoch>: │ │ │

(alterações da Debian) <versão_upstream>- │ │ │

<versão.debian>.diff.gz │ │ │

├────────────────────────┼─────────────────────────────────────┤

O pacote fonte 3.0 <nome_de_pacote>_<epoch>: │ │ │

(quilt) (alterações da <versão_upstream>- │ │ │

Debian) <versão.debian>.debian.tar.gz │ │ │

├────────────────────────┼─────────────────────────────────────┤

O pacote fonte <nome_do_pacote>_<epoch>: │ │ │

(descrição) <versão_upstream>-<versão.debian>.dsc│ │ │

└────────────────────────┴─────────────────────────────────────┘

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

Page 216: Referências Debian

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

Você pode verificar a ordem de versão de pacotes pelo dpkg(1),

ex., "dpkg --compare-versions 7.0 gt 7.~pre1 ; echo $?" .

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

Page 217: Referências Debian

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/ lista de ficheiros de configuração.│ │ │

Page 218: Referências Debian

<nome_do_pacote>.conffiles (modificável pelo utilizador) │ │ │

├──────────────────────────┼───────────────────────────────────┤

/var/lib/dpkg/info/ lista de ficheiros e directórios │ │ │

<nome_do_pacote>.list instalados pelo pacote │ │ │

├──────────────────────────┼───────────────────────────────────┤

/var/lib/dpkg/info/ lista de valores de hash MD5 para │ │ │

<nome_do_pacote>.md5sums os ficheiros instalados pelo pacote│ │ │

├──────────────────────────┼───────────────────────────────────┤

/var/lib/dpkg/info/ script de pacote executado antes da│ │ │

<nome_do_pacote>.preinst instalação do pacote │ │ │

├──────────────────────────┼───────────────────────────────────┤

/var/lib/dpkg/info/ script de pacote executado após a │ │ │

<nome_do_pacote>.postinst instalação do pacote │ │ │

├──────────────────────────┼───────────────────────────────────┤

/var/lib/dpkg/info/ script de pacote executado antes da│ │ │

<nome_do_pacote>.prerm remoção do pacote │ │ │

├──────────────────────────┼───────────────────────────────────┤

/var/lib/dpkg/info/ script de pacote executado após a │ │ │

<nome_do_pacote>.postrm remoção do pacote │ │ │

├──────────────────────────┼───────────────────────────────────┤

/var/lib/dpkg/info/ script de pacote para o sistema │ │ │

<nome_do_pacote>.config debconf │ │ │

├──────────────────────────┼───────────────────────────────────┤

/var/lib/dpkg/alternatives a informação alternativa usada pelo│ │ │

Page 219: Referências Debian

/<nome_do_pacote> comando update-alternatives │ │ │

├──────────────────────────┼───────────────────────────────────┤

/var/lib/dpkg/available a informação de disponibilidade │ │ │

para todos os pacotes │ │ │

├──────────────────────────┼───────────────────────────────────┤

a informação de diversões usada │ │ │

/var/lib/dpkg/diversions pelo dpkg(1) e definida pelo │ │ │

`dpkg-divert`(8) │ │ │

├──────────────────────────┼───────────────────────────────────┤

a informação de estado de │ │ │

/var/lib/dpkg/statoverride 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" │ │ │

├──────────────────────────┼───────────────────────────────────┤

o backup de segunda geração e os │ │ │

/var/backups/dpkg.status* mais antigos do ficheiro "var/lib/ │ │ │

dpkg/status" │ │ │

└──────────────────────────┴───────────────────────────────────┘

Page 220: Referências Debian

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

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

Page 221: Referências Debian

*+ 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

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

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

Page 222: Referências Debian

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

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

Page 223: Referências Debian

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

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>

Page 224: Referências Debian

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

Page 225: Referências Debian

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

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

Page 226: Referências 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

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

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

Page 227: Referências Debian

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

Page 228: Referências Debian

# 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

Page 229: Referências Debian

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

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 squeeze-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.

Page 230: Referências Debian

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

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○

Page 231: Referências Debian

"libc")

related utility program version compatibility○

compatibilidade da ABI do Kernel○

Compatibilidade C++ ABI○

…○

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

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

Page 232: Referências Debian

some archives which should not be used as the automatic source

of upgrades are marked as NotAutomatic and dealt properly.

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

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

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.

Page 233: Referências Debian

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

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

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

Page 234: Referências Debian

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.

Page 235: Referências Debian

"/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

Page 236: Referências Debian

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

Page 237: Referências Debian

unstable archive.

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

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

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.

Page 238: Referências Debian

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

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

Page 239: Referências Debian

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. Updates and Backports

There are squeeze-updates and backports.debian.org archives

which provide updgrade packages for stable (squeeze).

Atenção

Do not use all packages available in the NotAutomatic archives

such as squeeze-backports. Use only selected packages which fits

your needs.

Here is an example of apt-pinning technique to include specific

newer upstream version packages found in squeeze-backports while

Page 240: Referências Debian

tracking squeeze and squeeze-updates. 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://ftp.us.debian.org/debian/ squeeze-updates 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 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 backports.debian.org archive

unless you wish to track particular packages in it 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>

Page 241: Referências Debian

Pin: release o=Backports.org archive

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-updates, o=Debian

Pin-Priority: 500

Package: *

Pin: release a=squeeze-backports, o=Backports.org archive

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

Page 242: Referências Debian

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

Page 243: Referências Debian

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

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

Page 244: Referências Debian

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

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"

Page 245: Referências Debian

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.

Page 246: Referências Debian

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

Page 247: Referências Debian

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 │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.3, caching proxy server for Debian │ │ │ │ │

approx * I:0.3 3896 archive files (compiled OCaml │ │ │ │ │

program) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

apt-cacher * V:0.3, 308 Caching proxy for Debian package│ │ │ │ │

Page 248: Referências Debian

I:0.4 and source files (Perl program) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

apt-cacher-ng V:0.3, Proxy de cache para distribuição│ │ │ │ │

* I:0.4 1092 de pacotes de software (programa│ │ │ │ │

C++ compilado) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.12, Proxy Bittorrent para │ │ │ │ │

debtorrent * I:0.17 1185 descarregar pacotes Debian │ │ │ │ │

(programa Python) │ │ │ │ │

└─────────────┴───────┴───────┴────────────────────────────────┘

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.

Page 249: Referências Debian

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 [email protected]

$ gpg --gen-key

...

$ gpg -K

...

sec 1024D/3A3CB5A6 2008-08-14

uid Foo (ARCHIVE KEY) <[email protected]>

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

Page 250: Referências Debian

$ 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

Page 251: Referências Debian

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'} = {

Page 252: Referências Debian

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 [email protected] 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

Page 253: Referências Debian

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

Page 254: Referências Debian

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

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

Page 255: Referências Debian

# 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.

Documentações principais sobre a gestão de pacotes:●

aptitude(8), dpkg(1), tasksel(8), apt-get(8), apt-config○

(8), apt-key(8), sources.list(5), apt.conf(5), e

apt_preferences(5);

"/usr/share/doc/apt-doc/guide.html/index.html" e "/usr/○

share/doc/apt-doc/offline.html/index.html" do pacote

apt-doc; e

"/usr/share/doc/aptitude/html/en/index.html" do pacote○

aptitude-doc-en.

Documentações oficiais e detalhadas no arquivo Debian:●

"Manual de Política Debian Capítulo 2 - O Arquivo○

Debian",

"Referência dos Programadores de Debian, Capítulo 4 -○

Recursos para Programadores de Debian 4.6 O Arquivo

Debian", e

Page 256: Referências Debian

"A FAQ de Debian GNU/Linux, Capítulo 5 - Os arquivos FTP○

de Debian".

Tutorial para construir um pacote Debian para utilizadores●

da Debian:

"Guia dos Novos Maintainers de Debian".○

Capítulo 3. A inicialização do sistema

It is wise for you as the system administrator to know roughly

how the Debian system is started and configured. Although the

exact details are in the source files of the packages installed

and their documentations, it is a bit overwhelming for most of

us.

I did my best to provide a quick overview of the key points of

the Debian system and their configuration for your reference,

based on the current and previous knowledge of mine and others.

Since the Debian system is a moving target, the situation over

the system may have been changed. Before making any changes to

the system, you should refer to the latest documentation for

each package.

3.1. Uma visão geral do processo de boot strap

O sistema do computador passa por várias fases de processos de

boot strap desde o ligar da energia até que oferece o sistema

operativo (OS) totalmente funcional ao utilizador.

Page 257: Referências Debian

Para simplicidade, eu limito a discussão à plataforma PC típica

com a instalação predefinida.

O processo de boot strap típico é como um foguete de quatro

etapas. Cada etapa do foguete entrega o controle do sistema à

próxima etapa.

Secção 3.2, “Estágio 1: a BIOS”●

Secção 3.3, “Estágio 2: o gestor de arranque”●

Secção 3.4, “Estágio 3: o sistema Debian mini”●

Secção 3.5, “Estágio 4: o sistema Debian normal”●

Of course, these can be configured differently. For example, if

you compiled your own kernel, you may be skipping the step with

the mini-Debian system. So please do not assume this is the case

for your system until you check it yourself.

Nota

For non-legacy PC platform such as the SUN or the Macintosh

system, the BIOS on ROM and the partition on the disk may be

quite different (Secção 9.3.1, “Configuração das partições do

disco”). Please seek the platform specific documentations

elsewhere for such a case.

3.2. Estágio 1: a BIOS

A BIOS é o 1ª etapa do processo de boot que é iniciado com o

evento de ligar a energia. A BIOS que reside na read only memory

Page 258: Referências Debian

(ROM) é executada a partir de um endereço de memória particular

no qual o contador de programa da CPU é inicializado pelo evento

de ligar a energia.

Esta BIOS executa a inicialização básica do hardware (POST:

power on self test) e entrega o controle do sistema ao próximo

passo que você disponibiliza. A BIOS é normalmente

disponibilizada com o hardware.

The BIOS startup screen usually indicates what key(s) to press

to enter the BIOS setup screen to configure the BIOS behavior.

Popular keys used are F1, F2, F10, Esc, Ins, and Del. If your

BIOS startup screen is hidden by a nice graphics screen, you may

press some keys such as Esc to disable this. These keys are

highly dependent on the hardware.

A localização do hardware e prioridade do código iniciado pela

BIOS pode ser seleccionado no écran de configuração da BIOS.

Tipicamente, os primeiros poucos sectores do primeiro

dispositivo seleccionado encontrado (disco rijo, disquete,

CD-ROM, ...) são carregados para a memória e este código inicial

é executado. Este código inicial pode ser um dos seguintes.

O código do gestor de arranque●

The kernel code of the stepping stone OS such as FreeDOS●

The kernel code of the target OS if it fits in this small●

space

Typically, the system is booted from the specified partition of

Page 259: Referências Debian

the primary hard disk partition. First 2 sectors of the hard

disk on legacy PC contain the master boot record (MBR). The disk

partition information including the boot selection is recorded

at the end of this MBR. The first boot loader code executed from

the BIOS occupies the rest of this MBR.

3.3. Estágio 2: o gestor de arranque

The boot loader is the 2nd stage of the boot process which is

started by the BIOS. It loads the system kernel image and the

initrd image to the memory and hands control over to them. This

initrd image is the root filesystem image and its support

depends on the bootloader used.

O sistema Debian normalmente usa o kernel Linux como kernel

predefinido do sistema. A imagem initrd para o kernel Linux 2.6

actual é tecnicamente a initramfs (sistema de ficheiros de RAM

inicial). A imagem initramfs é um arquivo cpio gzipado de

ficheiros no sistema de ficheiros raiz.

A instalação predefinida do sistema Debian coloca código da

primeira etapa do gestor de arranque GRUB no MBR para a

plataforma PC. Existem muitos gestores de arranque e opções de

configuração disponíveis.

Tabela 3.1. Lista de gestores de arranque

┌────────┬──────────────┬───────┬───────┬─────────┬───────────────┐

Page 260: Referências Debian

gestor │ │ │ │ │ │ │

de pacote popcon tamanho initrd descrição │ │ │ │ │ │ │

arranque │ │ │ │ │ │ │

├────────┼──────────────┼───────┼───────┼─────────┼───────────────┤

Isto │ │ │ │ │ │ │

suficientemente│ │ │ │ │ │ │

inteligente │ │ │ │ │ │ │

para │ │ │ │ │ │ │

compreender │ │ │ │ │ │ │

GRUB grub-legacy * V:0.4, 1984 Suportado partições de │ │ │ │ │ │ │

Legacy I:1.1 disco e │ │ │ │ │ │ │

sistemas de │ │ │ │ │ │ │

ficheiros como │ │ │ │ │ │ │

vfat, ext3, ...│ │ │ │ │ │ │

(predefinição │ │ │ │ │ │ │

em lenny │ │ │ │ │ │ │

├────────┼──────────────┼───────┼───────┼─────────┼───────────────┤

Isto │ │ │ │ │ │ │

suficientemente│ │ │ │ │ │ │

inteligente │ │ │ │ │ │ │

para │ │ │ │ │ │ │

GRUB 2 grub-pc * V:7, 2480 Suportado compreender │ │ │ │ │ │ │

I:25 partições de │ │ │ │ │ │ │

disco e │ │ │ │ │ │ │

sistemas de │ │ │ │ │ │ │

ficheiros como │ │ │ │ │ │ │

vfat, ext3, ...│ │ │ │ │ │ │

Page 261: Referências Debian

├────────┼──────────────┼───────┼───────┼─────────┼───────────────┤

Isto são │ │ │ │ │ │ │

imagens de │ │ │ │ │ │ │

arranque de │ │ │ │ │ │ │

GRUB 2 grub-rescue-pc V:0.04, 3896 Suportado recuperação do │ │ │ │ │ │ │

* I:0.5 GRUB 2 (CD ou │ │ │ │ │ │ │

disquete) │ │ │ │ │ │ │

(Versão PC/ │ │ │ │ │ │ │

BIOS) │ │ │ │ │ │ │

├────────┼──────────────┼───────┼───────┼─────────┼───────────────┤

Isto baseia-se │ │ │ │ │ │ │

nas │ │ │ │ │ │ │

Lilo lilo * V:0.5, 1236 Suportado localizações de│ │ │ │ │ │ │

I:2 sectores de │ │ │ │ │ │ │

dados no disco │ │ │ │ │ │ │

rijo. (Antigo) │ │ │ │ │ │ │

├────────┼──────────────┼───────┼───────┼─────────┼───────────────┤

Isto compreende│ │ │ │ │ │ │

o sistema de │ │ │ │ │ │ │

Isolinux syslinux * V:1.3, 204 Suportado ficheiros │ │ │ │ │ │ │

I:8 ISO9660. É │ │ │ │ │ │ │

usado pelo CD │ │ │ │ │ │ │

de arranque. │ │ │ │ │ │ │

├────────┼──────────────┼───────┼───────┼─────────┼───────────────┤

Isto compreende│ │ │ │ │ │ │

o sistema de │ │ │ │ │ │ │

Syslinux syslinux * V:1.3, 204 Suportado ficheiros MSDOS│ │ │ │ │ │ │

Page 262: Referências Debian

I:8 (FAT). É usado │ │ │ │ │ │ │

pela disquete │ │ │ │ │ │ │

de arranque. │ │ │ │ │ │ │

├────────┼──────────────┼───────┼───────┼─────────┼───────────────┤

Novo sistema é │ │ │ │ │ │ │

V:0.03, iniciado a │ │ │ │ │ │ │

Loadlin loadlin * I:0.2 144 Suportado partir do │ │ │ │ │ │ │

sistema FreeDOS│ │ │ │ │ │ │

/MSDOS. │ │ │ │ │ │ │

├────────┼──────────────┼───────┼───────┼─────────┼───────────────┤

Isto é software│ │ │ │ │ │ │

livre que │ │ │ │ │ │ │

MBR por substitui o MBR│ │ │ │ │ │ │

Neil mbr * V:0.8, 96 Não do MSDOS. Isto │ │ │ │ │ │ │

Turton I:5 suportado apenas │ │ │ │ │ │ │

compreende │ │ │ │ │ │ │

partições de │ │ │ │ │ │ │

disco. │ │ │ │ │ │ │

└────────┴──────────────┴───────┴───────┴─────────┴───────────────┘

Atenção

Do not play with boot loaders without having bootable rescue

media (CD or floppy) created from images in the grub-rescue-pc

package. It makes you boot your system even without functioning

bootloader on the hard disk.

Page 263: Referências Debian

Para o GRUB Legacy, o ficheiro de configuração do menu está

localizado em "/boot/grub/menu.lst". Por exemplo, tem entradas

como a seguinte.

title Debian GNU/Linux

root (hd0,2)

kernel /vmlinuz root=/dev/hda3 ro

initrd /initrd.img

For GRUB 2, the menu configuration file is located at "/boot/

grub/grub.cfg". It is automatically generated by "/usr/sbin/

update-grub" using templates from "/etc/grub.d/*" and settings

from "/etc/default/grub". For example, it has entries as the

following.

menuentry "Debian GNU/Linux" {

set root=(hd0,3)

linux /vmlinuz root=/dev/hda3

initrd /initrd.img

}

Para estes exemplos, estes parâmetros do GRUB significam o

seguinte.

Tabela 3.2. O significado dos parâmetros do GRUB

┌─────────┬────────────────────────────────────────────────────┐

Page 264: Referências Debian

Parâmetro significado │ │ │

do GRUB │ │ │

├─────────┼────────────────────────────────────────────────────┤

root usa a 3ª partição no disco primário a defini-la como│ │ │

"(hd0,2)" no GRUB Legacy ou como "(hd0,3)" no GRUB 2│ │ │

├─────────┼────────────────────────────────────────────────────┤

kernel usa o kernel localizado em "/vmlinuz" com parâmetro │ │ │

de kernel: "root=/dev/hda3 ro" │ │ │

├─────────┼────────────────────────────────────────────────────┤

initrd usa a imagem initrd/initramfs localizada em "/ │ │ │

initrd.img" │ │ │

└─────────┴────────────────────────────────────────────────────┘

Nota

O valor do número de partição usado pelo programa GRUB legacy é

menos um que o normal usado pelo kernel Linux e ferramentas

utilitárias. O programa GRUB 2 corrige este problema.

Dica

UUID (see Secção 9.3.2, “Aceder a partição usando UUID”) may be

used to identify a block special device instead of its file name

such as "/dev/hda3", e.g."root=UUID=

81b289d5-4341-4003-9602-e254a17ac232 ro".

Page 265: Referências Debian

Dica

Você pode iniciar um gestor de arranque a partir de outro gestor

de arranque usando técnicas chamadas chain loading.

Veja "info grub" e grub-install(8).

3.4. Estágio 3: o sistema Debian mini

The mini-Debian system is the 3rd stage of the boot process

which is started by the boot loader. It runs the system kernel

with its root filesystem on the memory. This is an optional

preparatory stage of the boot process.

Nota

The term "the mini-Debian system" is coined by the author to

describe this 3rd stage boot process for this document. This

system is commonly referred as the initrd or initramfs system.

Similar system on the memory is used by the Debian Installer.

The "/init" script is executed as the first program in this root

filesystem on the memory. It is a shell script program which

initializes the kernel in user space and hands control over to

the next stage. This mini-Debian system offers flexibility to

the boot process such as adding kernel modules before the main

boot process or mounting the root filesystem as an encrypted

one.

Page 266: Referências Debian

You can interrupt this part of the boot process to gain root

shell by providing "break=init" etc. to the kernel boot

parameter. See the "/init" script for more break conditions.

This shell environment is sophisticated enough to make a good

inspection of your machine's hardware.

Commands available in this mini-Debian system are stripped down

ones and mainly provided by a GNU tool called busybox(1).

Cuidado

Você precisa de usar a opção "-n" para o comando mount quando

está no sistema de ficheiros raiz apenas de leitura.

3.5. Estágio 4: o sistema Debian normal

Tabela 3.3. Lista de utilitários de arranque para o sistema

Debian

┌────────────────┬───────┬───────┬─────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

initscripts * V:91, 284 scripts para inicializar e │ │ │ │ │

I:99 desligar o sistema │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

sysvinit * V:85, 208 utilitários de init(8) estilo│ │ │ │ │

I:99 System-V │ │ │ │ │

Page 267: Referências Debian

├────────────────┼───────┼───────┼─────────────────────────────┤

sysv-rc * V:91, 300 mecanismo de mudança de │ │ │ │ │

I:99 runlevel estilo System-V │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

sysvinit-utils * V:91, 224 utilitários estilo System-V │ │ │ │ │

I:99 (startpar(8), bootlogd(8), …)│ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

V:91, Linux Standard Base │ │ │ │ │

lsb-base * I:99 36 funcionalidade de script de │ │ │ │ │

init 3.2 │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

ferramenta para organizar a │ │ │ │ │

insserv * V:22, 292 sequência de arranque usando │ │ │ │ │

I:26 dependências dos scripts │ │ │ │ │

init.d LSB │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

V:0.15, daemon de eventos baseado em │ │ │ │ │

upstart * I:0.2 700 init(8) para a concorrência │ │ │ │ │

(alternativa a sysvinit) │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

readahead-fedora V:0.3, readahead(8) para │ │ │ │ │

* I:0.5 144 pré-carregar os ficheiros do │ │ │ │ │

processo de arranque │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

ferramentas para usar a │ │ │ │ │

Page 268: Referências Debian

uswsusp * V:4, 536 suspensão de software no │ │ │ │ │

I:14 espaço de utilizador │ │ │ │ │

disponibilizadas pelo Linux │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

kexec-tools * V:0.17, 320 kexec tool for kexec(8) │ │ │ │ │

I:0.5 reboots (warm reboot) │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

bootchart * V:0.13, 132 analisador de performance do │ │ │ │ │

I:0.7 processo de arranque │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

V:0.10, analisador de performance do │ │ │ │ │

bootchart-view * I:0.6 280 processo de arranque │ │ │ │ │

(visualização) │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

mingetty * V:0.2, 64 getty(8) apenas de consola │ │ │ │ │

I:0.5 │ │ │ │ │

├────────────────┼───────┼───────┼─────────────────────────────┤

mgetty * V:0.19, 416 substituto inteligente de │ │ │ │ │

I:0.6 modem getty(8) │ │ │ │ │

└────────────────┴───────┴───────┴─────────────────────────────┘

Nota

This section describes classical System V style boot system on

Page 269: Referências Debian

lenny. Debian is moving to the event driven boot system. See The

future of the boot system in Debian and Dependency based boot

sequence.

Dica

All boot mechanisms are compatible through "/etc/init.d/rc", "/

etc/init.d/rcS", "/usr/sbin/update-rc.d", and "/usr/sbin/

invoke-rc.d" scripts.

Dica

O pacote readahead-fedora pode acelerar o arranque de um sistema

com uma quantidade decente de DRAM.

The normal Debian system is the 4th stage of the boot process

which is started by the mini-Debian system. The system kernel

for the mini-Debian system continues to run in this environment.

The root filesystem is switched from the one on the memory to

the one on the real hard disk filesystem.

The "/sbin/init" program is executed as the first program and

performs the main boot process. The Debian normally uses the

traditional sysvinit scheme with the sysv-rc package. See init

(8), inittab(5), and "/usr/share/doc/sysv-rc/

README.runlevels.gz" for the exact explanation. This main boot

process essentially goes through the following.

1. The Debian system goes into runlevel N (none) to initialize

Page 270: Referências Debian

the system by following the "/etc/inittab" description.

2. The Debian system goes into runlevel S to initialize the

system under the single-user mode to complete hardware

initialization etc.

3. O sistema Debian vai para um dos runlevels de

multi-utilizador (2 a 5) especificado para arrancar os

serviços do sistema.

The initial runlevel used for multi-user mode is specified with

the "init=" kernel boot parameter or in the "initdefault" line

of the "/etc/inittab". The Debian system as installed starts at

the runlevel 2.

Todos os ficheiros script actuais executados pelo sistema init

estão localizados no directório "/etc/init.d/".

3.5.1. O significado do runlevel

Cada runlevel usa um directório para a sua configuração e tem um

significado específico como o seguinte.

Tabela 3.4. Lista de runlevels e descrição da sua utilização

┌────────┬──────────┬──────────────────────────────────────────┐

runlevel directório descrição da utilização do runlevel │ │ │ │

├────────┼──────────┼──────────────────────────────────────────┤

N nenhum arranque do sistema em NENHUM nível │ │ │ │

(nenhum directório "/etc/rcN.d/") │ │ │ │

Page 271: Referências Debian

├────────┼──────────┼──────────────────────────────────────────┤

0 /etc/rc0.d parar o sistema │ │ │ │

/ │ │ │ │

├────────┼──────────┼──────────────────────────────────────────┤

S /etc/rcS.d modo de utilizador singular no arranque │ │ │ │

/ (alias: "s") │ │ │ │

├────────┼──────────┼──────────────────────────────────────────┤

1 /etc/rc1.d modo de utilizador singular trocado a │ │ │ │

/ partir do modo de multi utilizador │ │ │ │

├────────┼──────────┼──────────────────────────────────────────┤

2 /etc/rc2.d modo de multi-utilizador │ │ │ │

/ │ │ │ │

├────────┼──────────┼──────────────────────────────────────────┤

3 /etc/rc3.d ,, │ │ │ │

/ │ │ │ │

├────────┼──────────┼──────────────────────────────────────────┤

4 /etc/rc4.d ,, │ │ │ │

/ │ │ │ │

├────────┼──────────┼──────────────────────────────────────────┤

5 /etc/rc5.d ,, │ │ │ │

/ │ │ │ │

├────────┼──────────┼──────────────────────────────────────────┤

6 /etc/rc6.d reiniciar o sistema │ │ │ │

/ │ │ │ │

Page 272: Referências Debian

├────────┼──────────┼──────────────────────────────────────────┤

7 /etc/rc7.d modo de multi-utilizador válido mas │ │ │ │

/ normalmente não usado │ │ │ │

├────────┼──────────┼──────────────────────────────────────────┤

8 /etc/rc8.d ,, │ │ │ │

/ │ │ │ │

├────────┼──────────┼──────────────────────────────────────────┤

9 /etc/rc9.d ,, │ │ │ │

/ │ │ │ │

└────────┴──────────┴──────────────────────────────────────────┘

Você pode mudar o runlevel a partir da consola para, por exemplo

4, com o seguinte.

$ sudo telinit 4

Cuidado

The Debian system does not pre-assign any special meaning

differences among the runlevels between 2 and 5. The system

administrator on the Debian system may change this. (I.e.,

Debian is not Red Hat Linux nor Solaris by Sun Microsystems nor

HP-UX by Hewlett Packard nor AIX by IBM nor …)

Cuidado

Page 273: Referências Debian

The Debian system does not populate directories for the

runlevels between 7 and 9 when the package is installed.

Traditional Unix variants don't use these runlevels.

3.5.2. A configuração do runlevel

Nota

In Debian squeeze, dependency based boot order provided by the

insserv package is used instead of classical alphabetical one.

The "CONCURRENCY" value in "/etc/default/rcS" controls its

concurrency: "none" for no concurrency, "startpar" for

concurrency within the same sequence number, or "makefile" for

full concurrency. See "/usr/share/doc/insserv/README.Debian".

The name of the symlink in each runlevel directory has the form

"S<2-digit-number><original-name>" or "K<2-digit-number>

<original-name>". The 2-digit-number is used to determine the

order in which to run the scripts. "S" is for "Start" and "K" is

for "Kill".

For "CONCURRENCY=none", when init(8) or telinit(8) commands goes

into the runlevel to "<n>", it execute following scripts.

1. The script names starting with a "K" in "/etc/rc<n>.d/" are

executed in alphabetical order with the single argument

"stop". (killing services)

2. The script names starting with an "S" in "/etc/rc<n>.d/" are

executed in alphabetical order with the single argument

Page 274: Referências Debian

"start". (starting services)

For example, if you had the links "S10sysklogd" and "S20exim4"

in a runlevel directory, "S10sysklogd" which is symlinked to "..

/init.d/sysklogd" would run before "S20exim4" which is symlinked

to "../init.d/exim4".

For "CONCURRENCY=makefile" (new default), package dependency

defined in the header of init scripts are used to order them.

Atenção

It is not advisable to make any changes to symlinks in "/etc/

rcS.d/" unless you know better than the maintainer.

3.5.3. O exemplo de gestão do runlevel

Por exemplo, vamos configurar o sistema runleve algo como o Red

Hat Linux com o seguinte.

init arranca o sistema em runlevel=3 por predefinição●

O init não arranca o gdm(1) nos runlevel (0,1,2,6).●

init arranca o gdm(1) em runlevel=(3,4,5).●

This can be done by using editor on the "/etc/inittab" file to

change starting runlevel and using user friendly runlevel

management tools such as sysv-rc-conf or bum to edit the

runlevel. If you are to use command line only instead, here is

how you do it (after the default installation of the gdm package

Page 275: Referências Debian

and selecting it to be the choice of display manager).

# cd /etc/rc2.d ; mv S21gdm K21gdm

# cd /etc ; perl -i -p -e 's/^id:.:/id:3:/' inittab

Please note the "/etc/X11/default-display-manager" file is

checked when starting the display manager daemons: xdm, gdm,

kdm, and wdm.

Nota

Você ainda pode arrancar o X a partir de qualquer consola de

shell com o comando startx(1).

3.5.4. O parâmetro predefinido para cada script de init

The default parameter for each init script in "/etc/init.d/" is

given by the corresponding file in "/etc/default/" which

contains environment variable assignments only. This choice of

directory name is specific to the Debian system. It is roughly

the equivalent of the "/etc/sysconfig" directory found in Red

Hat Linux and other distributions. For example, "/etc/default/

cron" can be used to control how "/etc/init.d/cron" works.

O ficheiro "/etc/default/rcS" pode ser usado para personalizar

as predefinições no momento de arranque para motd(5), sulogin

(8), etc.

Se não consegue obter o comportamento que deseja ao alterar tais

Page 276: Referências Debian

variáveis então você pode modificar os scripts de init. Estes

são ficheiros de configuração editáveis por administradores de

sistemas.

3.5.5. O nome da máquina

The kernel maintains the system hostname. The init script in

runlevel S which is symlinked to "/etc/init.d/hostname.sh" sets

the system hostname at boot time (using the hostname command) to

the name stored in "/etc/hostname". This file should contain

only the system hostname, not a fully qualified domain name.

Para escrever o nome de máquina actual corra hostname(1) sem

argumentos.

3.5.6. O sistema de ficheiros

Apesar do sistema de ficheiros raiz ser montado pelo kernel

quando arranca, outros sistemas de ficheiros são montados no

runlevel S pelos seguintes scripts de init.

"`/etc/init.d/mountkernfs.sh" para sistemas de ficheiros do●

kernel em "/proc", "/sys", etc.

"`/etc/init.d/mountdevsubfs.sh" para sistemas de ficheiros●

virtuais em "/dev"

"`/etc/init.d/mountall.sh" para sistemas de ficheiros●

normais usando o "/etc/fstab"

"`/etc/init.d/mountnfs.sh" para sistemas de ficheiros de●

rede usando o "/etc/fstab"

Page 277: Referências Debian

As opções de montagem do sistema de ficheiros são definidas em "

/etc/fstab". Veja Secção 9.3.5, “Optimização do sistema de

ficheiros por opções de montagem”.

Nota

A montagem actual de sistemas de ficheiros de rede espera que a

interface de rede arranque.

Atenção

Após montar todos os sistemas de ficheiros, os ficheiros

temporários em "/tmp", "/var/lock", e "/var/run" são limpos para

cada arranque.

3.5.7. Inicialização da interface de rede

As interfaces de rede são iniciadas no runlevel 5 pelo script de

init simbolicamente ligado a "/etc/init.d/ifupdown-clean" e "/

etc/init.d/ifupdown". Veja Capítulo 5, Configuração de rede para

como os configurar.

3.5.8. Inicialização do serviço de rede

Muitos serviços de rede (veja Capítulo 6, Aplicações de rede)

são iniciados sob modo de multi-utilizador directamente como

processos daemon durante o arranque pelo script de init, ex., "/

etc/rc2.d/S20exim4" (para RUNLEVEL=2) o que é um link simbólico

Page 278: Referências Debian

para "/etc/init.d/exim4".

Some network services can be started on demand using the

super-server inetd (or its equivalents). The inetd is started at

boot time by "/etc/rc2.d/S20inetd" (for RUNLEVEL=2) which is a

symlink to "/etc/init.d/inetd". Essentially, inetd allows one

running daemon to invoke several others, reducing load on the

system.

Whenever a request for service arrives at super-server inetd ,

its protocol and service are identified by looking them up in

the databases in "/etc/protocols" and "/etc/services". inetd

then looks up a normal Internet service in the "/etc/inetd.conf"

database, or a Open Network Computing Remote Procedure Call (ONC

RPC)/Sun RPC based service in "/etc/rpc.conf".

Sometimes, inetd does not start the intended server directly but

starts the TCP wrapper program, tcpd(8), with the intended

server name as its argument in "/etc/inetd.conf". In this case,

tcpd runs the appropriate server program after logging the

request and doing some additional checks using "/etc/hosts.deny"

and "/etc/hosts.allow".

Para segurança do sistema, desactive o máximo possível de

programas de serviço de rede. Veja Secção 4.6.3, “Restringindo

acesso a alguns serviços de servidor”.

Veja inetd(8), inetd.conf(5), protocols(5), services(5), tcpd

(8), hosts_access(5), hosts_options(5), rpcinfo(8), portmap(8),

Page 279: Referências Debian

e "/usr/share/doc/portmap/portmapper.txt.gz".

3.5.9. A mensagem do sistema

The system message can be customized by "/etc/default/syslogd"

and "/etc/syslog.conf" for both the log file and on-screen

display. See syslogd(8) and syslog.conf(5). See also

Secção 9.2.2, “Analizador de log”.

3.5.10. A mensagem do kernel

The kernel message can be customized by "/etc/default/klogd" for

both the log file and on-screen display. Set "KLOGD='-c 3'" in

this file and run "/etc/init.d/klogd restart". See klogd(8).

Você pode alterar directamente o nível de mensagens de erro

fazendo o seguinte.

# dmesg -n3

Tabela 3.5. Lista de níveis de erro do kernel

┌────────────────┬────────────────┬────────────────────────────┐

valor de nível nome de nível de significado │ │ │ │

de erro erro │ │ │ │

├────────────────┼────────────────┼────────────────────────────┤

0 KERN_EMERG sistema está inutilizável │ │ │ │

Page 280: Referências Debian

├────────────────┼────────────────┼────────────────────────────┤

1 KERN_ALERT acção tem de ser tomada │ │ │ │

imediatamente │ │ │ │

├────────────────┼────────────────┼────────────────────────────┤

2 KERN_CRIT condições críticas │ │ │ │

├────────────────┼────────────────┼────────────────────────────┤

3 KERN_ERR condições de erro │ │ │ │

├────────────────┼────────────────┼────────────────────────────┤

4 KERN_WARNING condições de aviso │ │ │ │

├────────────────┼────────────────┼────────────────────────────┤

5 KERN_NOTICE condição normal mas │ │ │ │

significante │ │ │ │

├────────────────┼────────────────┼────────────────────────────┤

6 KERN_INFO informativa │ │ │ │

├────────────────┼────────────────┼────────────────────────────┤

7 KERN_DEBUG mensagens de nível de │ │ │ │

depuração │ │ │ │

└────────────────┴────────────────┴────────────────────────────┘

3.5.11. O sistema udev

For Linux kernel 2.6, the udev system provides mechanism for the

automatic hardware discovery and initialization (see udev(7)).

Page 281: Referências Debian

Upon discovery of each device by the kernel, the udev system

starts a user process which uses information from the sysfs

filesystem (see Secção 1.2.12, “procfs e sysfs”), loads required

kernel modules supporting it using the modprobe(8) program (see

Secção 3.5.12, “A inicialização de módulos do kernel”), and

creates corresponding device nodes.

Dica

If "/lib/modules/<kernel-version>/modules.dep" was not generated

properly by depmod(8) for some reason, modules may not be loaded

as expected by the udev system. Execute "depmod -a" to fix it.

The name of device nodes can be configured by udev rule files in

"/etc/udev/rules.d/". Current default rules tend to create

dynamically generated names resulting non-static device names

except for cd and network devices. By adding your custom rules

similar to what cd and network devices do, you can generate

static device names for other devices such as USB memory sticks,

too. See "Writing udev rules" or "/usr/share/doc/udev/

writing_udev_rules/index.html".

Como o sistema udev é de certa maneira um alvo em movimento, eu

deixo os detalhes para outras documentações e descrevo a

informação mínima aqui.

Dica

Para regras de montagem em "/etc/fstab", os nós de dispositivo

Page 282: Referências Debian

não precisam de ser os estáticos. Você pode usar o UUID para

montar os dispositivos em vez dos nomes de dispositivo como "/

dev/sda". Veja Secção 9.3.2, “Aceder a partição usando UUID”.

3.5.12. A inicialização de módulos do kernel

The modprobe(8) program enables us to configure running Linux

kernel from user process by adding and removing kernel modules.

The udev system (see Secção 3.5.11, “O sistema udev”) automates

its invocation to help the kernel module initialization.

There are non-hardware modules and special hardware driver

modules as the following which need to be pre-loaded by listing

them in the "/etc/modules" file (see modules(5)).

Módulos TUN/TAP que disponibilizam dispositivos de rede●

Point-to-Point virtuais (TUN) e dispositivos de rede

Ethernet virtuais (TAP).

Módulos netfilter que disponibilizam capacidades de firewall●

netfilter (iptables(8), Secção 5.9, “Infraestrutura do

netfilter”), e

módulos de driver watchdog timer●

The configuration files for the modprobe(8) program are located

under the "/etc/modprobes.d/" directory as explained in

modprobe.conf(5). (If you want to avoid some kernel modules to

be auto-loaded, consider to blacklist them in the "/etc/

modprobes.d/blacklist" file.)

Page 283: Referências Debian

O ficheiro "/lib/modules/<version>/modules.dep" gerado pelo

programa depmod(8) descreve as dependências dos módulos usados

pelo programa modprobe(8).

Nota

If you experience module loading issues with boot time module

loading or with modprobe(8), "depmod -a" may resolve these

issues by reconstructing "modules.dep".

O programa modinfo(8) mostra informação sobre um módulo do

kernel Linux.

O programa lsmod(8) formata lindamente o conteúdo de "/proc/

modules", e mostra que módulos do kernel estão actualmente

carregados.

Dica

Você pode identificar o hardware exacto no seu sistema. Veja

Secção 9.6.3, “Identificação do hardware”.

Dica

Você pode configurar o hardware durante o arranque par activar

as funcionalidades esperadas do hardware. Veja Secção 9.6.4,

“Configuração do hardware”.

Dica

Page 284: Referências Debian

Você pode adicionar suporta para o seu dispositivo ao recompilar

o kernel. Veja Secção 9.7, “O kernel”.

Capítulo 4. Autenticação

When a person (or a program) requests access to the system,

authentication confirms the identity to be a trusted one.

Atenção

Configuration errors of PAM may lock you out of your own system.

You must have a rescue CD handy or setup an alternative boot

partition. To recover, boot the system with them and correct

things from there.

4.1. Autenticação Unix normal

Normal Unix authentication is provided by the pam_unix(8) module

under the PAM (Pluggable Authentication Modules). Its 3

important configuration files, with ":" separated entries, are

the following.

Tabela 4.1. 3 ficheiros de configuração importantes para

pam_unix(8)

┌────────┬──────────┬──────────┬──────┬────────────────────────┐

ficheiro permissão utilizador grupo descrição │ │ │ │ │ │

Page 285: Referências Debian

├────────┼──────────┼──────────┼──────┼────────────────────────┤

/etc/ -rw-r--r-- root root informação da conta do │ │ │ │ │ │

passwd utilizador (higienizada)│ │ │ │ │ │

├────────┼──────────┼──────────┼──────┼────────────────────────┤

/etc/ -rw-r----- root shadow informação segura da │ │ │ │ │ │

shadow conta do utilizador │ │ │ │ │ │

├────────┼──────────┼──────────┼──────┼────────────────────────┤

/etc/ -rw-r--r-- root root informação do grupo │ │ │ │ │ │

group │ │ │ │ │ │

└────────┴──────────┴──────────┴──────┴────────────────────────┘

"/etc/passwd" contém o seguinte.

...

utilizador1:x:1000:1000:Nome de Utilizador1,,,:/home/utilizador1:/bin/bash

utilizador2:x:1001:1001:Nome de Utilizador2,,,:/home/utilizador2:/bin/bash

...

Como explicado em passwd(5), cada entrada ":" separada neste

ficheiro significa o seguinte.

Nome de login●

Entrada de especificação de palavra-passe●

ID numérico do utilizador●

ID numérico do grupo●

Nome de utilizador ou campo de comentários●

Page 286: Referências Debian

Directório home do utilizador●

Interpretador de comandos opcional do utilizador●

A segunda entrada de "/etc/passwd" foi usada para a entrada de

palavra-passe encriptada. Após a introdução de "/etc/shadow",

esta entrada é usada para a entrada de especificação da

palavra-passe.

Tabela 4.2. A segunda entrada no conteúdo de "/etc/passwd"

┌────────┬────────────────────────────────────────────────┐

conteúdo significado │ │ │

├────────┼────────────────────────────────────────────────┤

(vazio) conta sem palavra-passe │ │ │

├────────┼────────────────────────────────────────────────┤

x a palavra-passe encriptada está em "/etc/shadow"│ │ │

├────────┼────────────────────────────────────────────────┤

* nenhum login para esta conta │ │ │

├────────┼────────────────────────────────────────────────┤

! nenhum login para esta conta │ │ │

└────────┴────────────────────────────────────────────────┘

"/etc/shadow" contém o seguinte.

Page 287: Referências Debian

...

user1:$1$Xop0FYH9$IfxyQwBe9b8tiyIkt2P4F/:13262:0:99999:7:::

user2:$1$vXGZLVbS$ElyErNf/agUDsm1DehJMS/:13261:0:99999:7:::

...

Como explicado em shadow(5), cada entrada ":" separada neste

ficheiro significa o seguinte.

Nome de login●

Palavra-passe encriptada (O "$1$" inicial indica o uso de●

encriptação MD5. O "*" indica nenhum login.)

Dias desde Jan 1, 1970 que essa palavra-passe foi alterada●

Dias antes da palavra-passe poder ser alterada●

Dias após os quais a palavra-passe tem de ser alterada●

Dias de aviso ao utilizador antes da palavra-passe expirar●

…●

"/etc/group" contém o seguinte.

grupo1:x:20:utilizador1,utilizador2

Como explicado em grupo(5), cada entrada ":" separada neste

ficheiro significa o seguinte.

Nome do grupo●

Palavra-passe encriptada (não usada na realidade)●

ID numérico do grupo●

lista separada por "," de nomes de utilizadores●

Page 288: Referências Debian

Nota

"/etc/gshadow" provides the similar function as "/etc/shadow"

for "/etc/group" but is not really used.

Nota

The actual group membership of a user may be dynamically added

if "auth optional pam_group.so" line is added to "/etc/pam.d/

common-auth" and set it in "/etc/security/group.conf". See

pam_group(8).

Nota

The base-passwd package contains an authoritative list of the

user and the group: "/usr/share/doc/base-passwd/

users-and-groups.html".

4.2. Gerir informação de conta e palavra-passe

Aqui estão alguns comandos notáveis para gerir informação de

conta

Tabela 4.3. Lista de comandos para gerir informação de conta

┌───────────────────────┬──────────────────────────────────────┐

comando função │ │ │

├───────────────────────┼──────────────────────────────────────┤

Page 289: Referências Debian

getent passwd navegar na informação da conta de " │ │ │

<nome_de_utilizador> <nome_de_utilizador>" │ │ │

├───────────────────────┼──────────────────────────────────────┤

getent shadow browse shadowed account information of│ │ │

<unome_de_utilizador> "<user_name>" │ │ │

├───────────────────────┼──────────────────────────────────────┤

getent group navegar na informação do grupo de " │ │ │

<nome_de_grupo> <nome_do_grupo>" │ │ │

├───────────────────────┼──────────────────────────────────────┤

passwd gere a palavra-passe da conta │ │ │

├───────────────────────┼──────────────────────────────────────┤

passwd -e definir palavra-passe de uma-vez para │ │ │

a activação da conta │ │ │

├───────────────────────┼──────────────────────────────────────┤

chage gerir a informação de envelhecimento │ │ │

da palavra-passe │ │ │

└───────────────────────┴──────────────────────────────────────┘

You may need to have the root privilege for some functions to

work. See crypt(3) for the password and data encryption.

Nota

On the system set up with PAM and NSS as the Debian alioth

Page 290: Referências Debian

machine, the content of local "/etc/passwd", "/etc/group" and "/

etc/shadow" may not be actively used by the system. Above

commands are valid even under such environment.

4.3. Boa palavra-passe

When creating an account during your system installation or with

the passwd(1) command, you should choose a good password which

consists of 6 to 8 characters including one or more characters

from each of the following sets according to passwd(1).

Alfabéticos de minúsculas●

Dígitos de 0 a 9●

Marcas de pontuação●

Atenção

Não escolha palavras que podem ser adivinhadas para a

palavra-passe.

4.4. Criando palavra-passe encriptada

Existem ferramentas independentes para gerar palavras-passe

encriptadas salgadas.

Tabela 4.4. Lista de ferramentas para gerar palavras-passe

┌───────┬──────┬───────┬────────┬──────────────────────────────┐

Page 291: Referências Debian

pacote popcon tamanho comando função │ │ │ │ │ │

├───────┼──────┼───────┼────────┼──────────────────────────────┤

V:10, frontend cheiro de │ │ │ │ │ │

whois * I:88 396 mkpasswd funcionalidades para a │ │ │ │ │ │

biblioteca crypt(3) │ │ │ │ │ │

├───────┼──────┼───────┼────────┼──────────────────────────────┤

openssl V:56, 2380 openssl compute password hashes │ │ │ │ │ │

* I:91 passwd (OpenSSL). passwd(1ssl) │ │ │ │ │ │

└───────┴──────┴───────┴────────┴──────────────────────────────┘

4.5. PAM e NSS

Modern Unix-like systems such as the Debian system provide PAM

(Pluggable Authentication Modules) and NSS (Name Service Switch)

mechanism to the local system administrator to configure his

system. The role of these can be summarizes as the following.

PAM offers a flexible authentication mechanism used by the●

application software thus involves password data exchange.

NSS offers a flexible name service mechanism which is●

frequently used by the C standard library to obtain the user

and group name for programs such as ls(1) and id(1).

These PAM and NSS systems need to be configured consistently.

Os pacotes notáveis dos sistemas PAM e NSS são os seguintes.

Page 292: Referências Debian

Tabela 4.5. Lista de sistemas PAM e NSS notáveis

┌───────────────────┬───────┬───────┬──────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├───────────────────┼───────┼───────┼──────────────────────────┤

libpam-modules * V:88, 1036 Pluggable Authentication │ │ │ │ │

I:99 Modules (serviço básico) │ │ │ │ │

├───────────────────┼───────┼───────┼──────────────────────────┤

V:2, Pluggable Authentication │ │ │ │ │

libpam-ldap * I:4 408 Module que permite │ │ │ │ │

interfaces LDAP │ │ │ │ │

├───────────────────┼───────┼───────┼──────────────────────────┤

V:2, Pluggable Authentication │ │ │ │ │

libpam-cracklib * I:2 104 Module para activar │ │ │ │ │

suporte a cracklib │ │ │ │ │

├───────────────────┼───────┼───────┼──────────────────────────┤

Pluggable Authentication │ │ │ │ │

libpam-doc * I:0.6 1208 Modules (documentação em │ │ │ │ │

html e texto) │ │ │ │ │

├───────────────────┼───────┼───────┼──────────────────────────┤

GNU C Library: Shared │ │ │ │ │

libc6 * V:97, 10012 libraries which also │ │ │ │ │

I:99 provides "Name Service │ │ │ │ │

Switch" service │ │ │ │ │

Page 293: Referências Debian

├───────────────────┼───────┼───────┼──────────────────────────┤

glibc-doc * I:3 2008 Biblioteca GNU C: Manuais │ │ │ │ │

(manpages) │ │ │ │ │

├───────────────────┼───────┼───────┼──────────────────────────┤

glibc-doc-reference Biblioteca GNU C: Manual │ │ │ │ │

* I:1.4 12156 de referência em info, pdf│ │ │ │ │

e html (não-livre) │ │ │ │ │

├───────────────────┼───────┼───────┼──────────────────────────┤

libnss-mdns * I:49 116 Módulo NSS para resolução │ │ │ │ │

de nomes Multicast DNS │ │ │ │ │

├───────────────────┼───────┼───────┼──────────────────────────┤

libnss-ldap * I:4 268 NSS module for using LDAP │ │ │ │ │

as a naming service │ │ │ │ │

├───────────────────┼───────┼───────┼──────────────────────────┤

V:0.18, NSS module for using LDAP │ │ │ │ │

libnss-ldapd * I:0.5 144 as a naming service (new │ │ │ │ │

folk of libnss-ldap) │ │ │ │ │

└───────────────────┴───────┴───────┴──────────────────────────┘

"The Linux-PAM System Administrators' Guide" in libpam-doc●

is essential for learning PAM configuration.

"System Databases and Name Service Switch" section in●

glibc-doc-reference is essential for learning NSS

configuration.

Page 294: Referências Debian

Nota

You can see more extensive and current list by "aptitude search

'libpam-|libnss-'" command. The acronym NSS may also mean

"Network Security Service" which is different from "Name Service

Switch".

Nota

PAM é a maneira mais básica de inicializar variáveis de ambiente

para cada programa com o valor predefinido de todo o sistema.

4.5.1. Ficheiros de configuração acedidos pelo PAM e NSS

Aqui estão alguns ficheiros de configuração notáveis acedidos

pelo PAM.

Tabela 4.6. Lista de ficheiros de configuração acedidos pelo PAM

┌──────────────────┬───────────────────────────────────────────┐

ficheiro de função │ │ │

configuração │ │ │

├──────────────────┼───────────────────────────────────────────┤

/etc/pam.d/ set up PAM configuration for the " │ │ │

<nome_do_programa> <program_name>" program; see pam(7) and │ │ │

pam.d(5) │ │ │

Page 295: Referências Debian

├──────────────────┼───────────────────────────────────────────┤

/etc/nsswitch.conf set up NSS configuration with the entry for│ │ │

each service. See nsswitch.conf(5) │ │ │

├──────────────────┼───────────────────────────────────────────┤

/etc/nologin limita o login de utilizador pelo módulo │ │ │

pam_nologin(8) │ │ │

├──────────────────┼───────────────────────────────────────────┤

/etc/securetty limita a tty para o acesso de root pelo │ │ │

módulo pam_securetty(8) │ │ │

├──────────────────┼───────────────────────────────────────────┤

/etc/security/ define limites de acesso pelo módulo │ │ │

access.conf pam_access(8) │ │ │

├──────────────────┼───────────────────────────────────────────┤

/etc/security/ define a restrição baseada em grupo pelo │ │ │

group.conf módulo pam_group(8) │ │ │

├──────────────────┼───────────────────────────────────────────┤

/etc/security/ define as variáveis de ambiente pelo módulo│ │ │

pam_env.conf pam_env(8) │ │ │

├──────────────────┼───────────────────────────────────────────┤

define variáveis de ambiente adicionais │ │ │

/etc/environment pelo módulo pam_env(8) com o argumento │ │ │

"readenv=1" │ │ │

├──────────────────┼───────────────────────────────────────────┤

/etc/default/ set locale by pam_env(8) module with the │ │ │

Page 296: Referências Debian

locale "readenv=1 envfile=/etc/default/locale" │ │ │

argument. (Debian) │ │ │

├──────────────────┼───────────────────────────────────────────┤

/etc/security/ set resource restraint (ulimit, core, …) by│ │ │

limits.conf the pam_linits(8) module │ │ │

├──────────────────┼───────────────────────────────────────────┤

/etc/security/ define a retenção de tempo pelo módulo │ │ │

time.conf pam_time(8) │ │ │

└──────────────────┴───────────────────────────────────────────┘

The limitation of the password selection is implemented by the

PAM modules, pam_unix(8) and pam_cracklib(8). They can be

configured by their arguments.

Dica

Os módulos PAM usam o sufixo ".so" para os seus nomes de

ficheiros.

4.5.2. O moderno sistema de gestão centralizado

The modern centralized system management can be deployed using

the centralized Lightweight Directory Access Protocol (LDAP)

server to administer many Unix-like and non-Unix-like systems on

the network. The open source implementation of the Lightweight

Directory Access Protocol is OpenLDAP Software.

Page 297: Referências Debian

The LDAP server provides the account information through the use

of PAM and NSS with libpam-ldap and libnss-ldap packages for the

Debian system. Several actions are required to enable this (I

have not used this setup and the following is purely secondary

information. Please read this in this context.).

You set up a centralized LDAP server by running program such●

as stand-alone LDAP daemon, slapd(8).

Você altera os ficheiros de configuração do PAM no●

directório "/etc/pam.d/" para usar "pam_ldap.so" em vez do

predefinido "pam_unix.so".

Debian usa "/etc/pam_ldap.conf" como ficheiro de○

configuração para libpam-ldap e "/etc/pam_ldap.secret"

como ficheiro para armazenar a palavra-passe do root.

Você altera a configuração do NSS no ficheiro "/etc/●

nsswitch.conf" para usar "ldap" em vez da predefinição

("compat" ou "file").

Debian usa o "/etc/libnss-ldap.conf" como o ficheiro de○

configuração para libnss-ldap.

Você tem de fazer libpam-ldap para usar a ligação SSL (ou●

TLS) para a segurança da palavra-passe.

You may make libnss-ldap to use SSL (or TLS) connection to●

ensure integrity of data at the cost of the LDAP network

overhead.

Você deve correr o nscd(8) localmente para colocar em cache●

quaisquer resultados de busca LDAP de modo a reduzir o

Page 298: Referências Debian

tráfego de rede do LDAP.

Veja as documentações em pam_ldap.conf(5) e "/usr/share/doc/

libpam-doc/html/" oferecidas pelo pacote libpam-doc e "info libc

'Name Service Switch'" oferecida pelo pacote glibc-doc.

De modo semelhante, você pode configurar sistemas centralizados

alternativos com outros métodos.

NIS (originalmente chamado YP) ou NIS+ com sistemas tipo●

Unix mais antigos

Winbind com Windows NT e SAMBA●

4.5.3. "Porque o su do GNU não suporta o grupo wheel"

This is the famous phrase at the bottom of the old "info su"

page by Richard M. Stallman. Not to worry: the current su

command in Debian uses PAM, so that one can restrict the ability

to use su to the root group by enabling the line with

"pam_wheel.so" in "/etc/pam.d/su".

4.5.4. Regras de palavra-passe rigorosas

Instalar o pacote libpam-cracklib permite-lhe forçar regras de

palavra-passe rigorosas, por exemplo, ao ter linhas activas em "

/etc/pam.d/common-password" como se segue.

Para lenny:

Page 299: Referências Debian

password required pam_cracklib.so retry=3 minlen=9 difok=3

password required pam_unix.so use_authtok nullok md5

Para squeeze:

password required pam_cracklib.so retry=3 minlen=9 difok=3

password [success=1 default=ignore] pam_unix.so use_authtok nullok md5

password requisite pam_deny.so

password required pam_permit.so

4.6. Outros controles de acesso

Nota

Veja Secção 9.5.15, “Tecla Alt-SysRq” para restringir a

funcionalidade do kernel chave de atenção segura (SAK).

4.6.1. sudo

sudo(8) is a program designed to allow a sysadmin to give

limited root privileges to users and log root activity. sudo

requires only an ordinary user's password. Install sudo package

and activate it by setting options in "/etc/sudoers". See

configuration example at "/usr/share/doc/sudo/examples/sudoers".

My usage of sudo for the single user system (see Secção 1.1.12,

“Configuração do sudo”) is aimed to protect myself from my own

stupidity. Personally, I consider using sudo a better

alternative to using the system from the root account all the

Page 300: Referências Debian

time. For example, the following changes the owner of "

<some_file>" to "<my_name>".

$ sudo chown <meu_nome> <qualquer_ficheiro>

Claro que se você conhecer a palavra-passe de root (como os

utilizadores de sistemas Debian auto-instalados conhecem),

qualquer comando pode ser executado sob root a partir da conta

de qualquer utilizador usando "su -c".

4.6.2. SELinux

Security-Enhanced Linux (SELinux) is a framework to tighten

privilege model tighter than the ordinary Unix-like security

model with the mandatory access control (MAC) policies. The root

power may be restricted under some conditions.

4.6.3. Restringindo acesso a alguns serviços de servidor

For system security, It is a good idea to disable as much server

programs as possible. This becomes critical for network servers.

Having unused servers, activated either directly as daemon or

via super-server program, are considered security risks.

Muito programas, como o sshd(8), usam controles de acesso

baseados no PAM. Existem muitas maneiras de restringir o acesso

a alguns serviços de servidor.

ficheiros de configuração: "/etc/default/<nome_do_programa>"●

Page 301: Referências Debian

configuração de runlevel para daemon●

PAM (Pluggable Authentication Modules)●

"/etc/inetd.conf" para super-server●

"/etc/hosts.deny" e "/etc/hosts.allow" para wrapper de TCP,●

tcpd(8)

"/etc/rpc.conf" para RPC da Sun●

"/etc/at.allow" e "/etc/at.deny" para atd(8)●

"/etc/cron.allow" e "/etc/cron.deny" para crontab(1)●

Firewall de Rede da infraestrutura netfilter●

Veja Secção 3.5.3, “O exemplo de gestão do runlevel”,

Secção 3.5.4, “O parâmetro predefinido para cada script de init”

, Secção 4.5.1, “Ficheiros de configuração acedidos pelo PAM e

NSS”, Secção 3.5.8, “Inicialização do serviço de rede”, e

Secção 5.9, “Infraestrutura do netfilter”.

Dica

os serviços Sun RPC precisam de estar activos para NFS e outros

programas baseados em RPC.

Dica

If you have problems with remote access in a recent Debian

system, comment out offending configuration such as "ALL:

PARANOID" in "/etc/hosts.deny" if it exists. (But you must be

careful on security risks involved with this kind of action.)

4.7. Segurança da autenticação

Page 302: Referências Debian

A informação aqui pode não ser suficiente para as suas

necessidades de segurança, mas deverá ser um bom começo.

4.7.1. Palavra-passe segura sobre a Internet

Many popular transportation layer services communicate messages

including password authentication in the plain text. It is very

bad idea to transmit password in the plain text over the wild

Internet where it can be intercepted. You can run these services

over "Transport Layer Security" (TLS) or its predecessor,

"Secure Sockets Layer" (SSL) to secure entire communication

including password by the encryption.

Tabela 4.7. Lista de serviços e portos inseguros e seguros

┌────────────────────────┬─────┬──────────────────────┬─────┐

nome do serviço inseguro porto nome do serviço seguro porto│ │ │ │ │

├────────────────────────┼─────┼──────────────────────┼─────┤

www (http) 80 https 443 │ │ │ │ │

├────────────────────────┼─────┼──────────────────────┼─────┤

smtp (mail) 25 ssmtp (smtps) 465 │ │ │ │ │

├────────────────────────┼─────┼──────────────────────┼─────┤

ftp-data 20 ftps-data 989 │ │ │ │ │

├────────────────────────┼─────┼──────────────────────┼─────┤

ftp 21 ftps 990 │ │ │ │ │

Page 303: Referências Debian

├────────────────────────┼─────┼──────────────────────┼─────┤

telnet 23 telnets 992 │ │ │ │ │

├────────────────────────┼─────┼──────────────────────┼─────┤

imap2 143 imaps 993 │ │ │ │ │

├────────────────────────┼─────┼──────────────────────┼─────┤

pop3 110 pop3s 995 │ │ │ │ │

├────────────────────────┼─────┼──────────────────────┼─────┤

ldap 389 ldaps 636 │ │ │ │ │

└────────────────────────┴─────┴──────────────────────┴─────┘

The encryption costs CPU time. As a CPU friendly alternative,

you can keep communication in plain text while securing just

password with the secure authentication protocol such as

"Authenticated Post Office Protocol" (APOP) for POP and

"Challenge-Response Authentication Mechanism MD5" (CRAM-MD5) for

SMTP and IMAP. (For sending mail messages over the Internet to

your mail server from your mail client, it is recently popular

to use new message submission port 587 instead of traditional

SMTP port 25 to avoid port 25 blocking by the network provider

while authenticating yourself with CRAM-MD5.)

4.7.2. Shell Segura

The Secure Shell (SSH) program provides secure encrypted

communications between two untrusted hosts over an insecure

Page 304: Referências Debian

network with the secure authentication. It consists of the

OpenSSH client, ssh(1), and the OpenSSH daemon, sshd(8). This

SSH can be used to tunnel the insecure protocol communication

such as POP and X securely over the Internet with the port

forwarding feature.

The client tries to authenticate itself using host-based

authentication, public key authentication, challenge-response

authentication, or password authentication. The use of public

key authentication enables the remote password-less login. See

Secção 6.9, “O servidor de acesso remoto e utilitário (SSH)”.

4.7.3. Medidas de segurança extra para a Internet

Even when you run secure services such as Secure Shell (SSH) and

Point-to-point tunneling protocol (PPTP) servers, there are

still chances for the break-ins using brute force password

guessing attack etc. from the Internet. Use of the firewall

policy (see Secção 5.9, “Infraestrutura do netfilter”) together

with the following secure tools may improve the security

situation.

Tabela 4.8. Lista de ferramentas para disponibilizar medidas de

segurança extra

┌─────────────┬───────┬───────┬────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

Page 305: Referências Debian

knockd * V:0.15, 164 pequeno daemon port-knock knockd│ │ │ │ │

I:0.3 (1) e cliente konck(1) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

denyhosts * V:2, 356 utility to help sysadmins thwart│ │ │ │ │

I:2 ssh hackers │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

fail2ban * V:4, 660 banir IPs que causam erros de │ │ │ │ │

I:5 autenticação múltipla │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

libpam-shield V:0.01, 104 bloquear atacantes remotos que │ │ │ │ │

* I:0.05 tentam adivinhar a palavra-passe│ │ │ │ │

└─────────────┴───────┴───────┴────────────────────────────────┘

4.7.4. Tornar a palavra-passe do root segura

Para prevenir que pessoas acedam à sua máquina com privilégios

de root, você precisa de tomar as seguintes acções.

Prevenir acesso físico ao disco rijo●

Bloquear a BIOS e prevenir o arranque a partir de medias●

amovíveis

Define palavra-passe para sessão interactiva do GRUB●

Bloquear o menu do GRUB de ser editado●

With physical access to hard disk, resetting the password is

relatively easy with following steps.

Page 306: Referências Debian

1. Mover o disco rijo para um PC com uma BIOS com arranque a

partir de CD.

2. Arrancar o sistema com uma media de recuperação (disco de

arranque Debian, CD Knoppix, CD GRUB, ...)

3. Montar a partição raiz com acesso de leitura/escrita.

4. Edit "/etc/passwd" in the root partition and make the second

entry for the root account empty.

If you have the edit access to the GRUB menu entry (see

Secção 3.3, “Estágio 2: o gestor de arranque”) for

grub-rescue-pc at the boot time, it is even easier with

following steps.

1. Boot system with the kernel parameter changed to something

like "root=/dev/hda6 rw init=/bin/sh".

2. Edit "/etc/passwd" and make the second entry for the root

account empty.

3. Reiniciar o sistema.

A shell de root do sistema está agora acessível sem

palavra-passe.

Nota

Once one has root shell access, he can access everything on the

system and reset any passwords on the system. Further more, he

may compromise password for all user accounts using brute force

password cracking tools such as john and crack packages (see

Page 307: Referências Debian

Secção 9.6.11, “Segurança do sistema e verificação de

integridade”). This cracked password may lead to compromise

other systems.

The only reasonable software solution to avoid all these

concerns is to use software encrypted root partition (or "/etc"

partition) using dm-crypt and initramfs (see Secção 9.4, “Dicas

de encriptação de dados”). You always need password to boot the

system, though.

Capítulo 5. Configuração de rede

Dica

For general guide to the GNU/Linux networking, read the Linux

Network Administrators Guide.

5.1. A infraestrutura de rede básica

Vamos rever a infraestrutura de rede básica do sistema Debian

moderno.

Tabela 5.1. Lista de ferramentas de configuração de rede

┌─────────────────────┬───────┬───────┬─────────────────┬────────────────┐

pacotes popcon tamanho tipo descrição │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

ferramenta │ │ │ │ │ │

Page 308: Referências Debian

standard para │ │ │ │ │ │

V:60, activar e │ │ │ │ │ │

ifupdown * I:99 228 config::ifupdown desactivar a │ │ │ │ │ │

rede │ │ │ │ │ │

(especificação │ │ │ │ │ │

da Debian) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

V:0.4, gerir a rede com│ │ │ │ │ │

ifplugd * I:0.9 244 , , fios │ │ │ │ │ │

automaticamente │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

script de testes│ │ │ │ │ │

V:0.04, de rede para │ │ │ │ │ │

ifupdown-extra * I:0.2 124 , , melhorar o │ │ │ │ │ │

pacote │ │ │ │ │ │

"ifupdown" │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

define métricas │ │ │ │ │ │

ifmetric * V:0.02, 100 , , de rota para uma│ │ │ │ │ │

I:0.10 interface de │ │ │ │ │ │

rede │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

mapear o script │ │ │ │ │ │

para melhorar o │ │ │ │ │ │

V:0.07, pacote │ │ │ │ │ │

guessnet * I:0.3 516 , , "ifupdown" via │ │ │ │ │ │

ficheiro "/etc/ │ │ │ │ │ │

Page 309: Referências Debian

network/ │ │ │ │ │ │

interfaces" │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

scripts de │ │ │ │ │ │

V:0.03, mapeamento para │ │ │ │ │ │

ifscheme * I:0.08 132 , , melhorar o │ │ │ │ │ │

pacote │ │ │ │ │ │

"ifupdown" │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

scripts da │ │ │ │ │ │

ifupdown-scripts-zg2 V:0.00, interface │ │ │ │ │ │

* I:0.04 232 , , Zugschlus para o│ │ │ │ │ │

método manual do│ │ │ │ │ │

ifupdown │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

NetworkManager │ │ │ │ │ │

network-manager * V:24, 2628 config::NM (daemon): gere a│ │ │ │ │ │

I:33 rede │ │ │ │ │ │

automaticamente │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

network-manager-gnome V:17, NetworkManager │ │ │ │ │ │

* I:29 5616 , , (frontend do │ │ │ │ │ │

GNOME) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

V:2, NetworkManager │ │ │ │ │ │

network-manager-kde * I:3 264 , , (frontend do │ │ │ │ │ │

Page 310: Referências Debian

KDE) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

NetworkManager │ │ │ │ │ │

cnetworkmanager * V:0.05, 208 , , (cliente de │ │ │ │ │ │

I:0.2 linha de │ │ │ │ │ │

comandos) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

gestor de rede │ │ │ │ │ │

wicd * V:0.5, 88 config::wicd com fios e sem │ │ │ │ │ │

I:2 fios │ │ │ │ │ │

(metapacote) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

gestor de rede │ │ │ │ │ │

V:0.04, com fios e sem │ │ │ │ │ │

wicd-cli * I:0.2 128 , , fios (cliente de│ │ │ │ │ │

linha de │ │ │ │ │ │

comandos) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

gestor de rede │ │ │ │ │ │

wicd-curses * V:0.15, 236 , , com fios e sem │ │ │ │ │ │

I:0.4 fios (cliente │ │ │ │ │ │

Curses) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

V:1.9, gestor de rede │ │ │ │ │ │

wicd-daemon * I:2 1780 , , com fios e sem │ │ │ │ │ │

fios (daemon) │ │ │ │ │ │

Page 311: Referências Debian

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

gestor de rede │ │ │ │ │ │

wicd-gtk * V:1.6, 772 , , com fios e sem │ │ │ │ │ │

I:2 fios (cliente │ │ │ │ │ │

GTK+) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

ferramentas │ │ │ │ │ │

V:27, administrativas │ │ │ │ │ │

iptables * I:99 1316 config::Netfilter para packet │ │ │ │ │ │

filtering e NAT │ │ │ │ │ │

(Netfilter) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

iproute2, IPv6 e│ │ │ │ │ │

outra │ │ │ │ │ │

iproute * V:41, 1044 config::iproute2 configuração de │ │ │ │ │ │

I:88 rede avançada: │ │ │ │ │ │

ip(8), tc(8), │ │ │ │ │ │

etc │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

renomear │ │ │ │ │ │

interfaces de │ │ │ │ │ │

ifrename * V:0.2, 236 , , rede baseado em │ │ │ │ │ │

I:0.6 vários critérios│ │ │ │ │ │

de estatística: │ │ │ │ │ │

ifrename(8) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

Page 312: Referências Debian

mostra ou altera│ │ │ │ │ │

ethtool * V:4, 208 , , as definições de│ │ │ │ │ │

I:13 um dispositivo │ │ │ │ │ │

Ethernet │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

test network │ │ │ │ │ │

reachability of │ │ │ │ │ │

iputils-ping * V:36, 96 test::iproute2 a remote host by│ │ │ │ │ │

I:99 hostname or IP │ │ │ │ │ │

address ( │ │ │ │ │ │

iproute2) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

test network │ │ │ │ │ │

V:0.6, reachability of │ │ │ │ │ │

iputils-arping * I:6 36 , , a remote host │ │ │ │ │ │

specified by the│ │ │ │ │ │

ARP address │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

rastreia o │ │ │ │ │ │

iputils-tracepath * V:0.4, 72 , , caminho de rede │ │ │ │ │ │

I:2 até uma máquina │ │ │ │ │ │

remota │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

conjunto de │ │ │ │ │ │

ferramentas de │ │ │ │ │ │

V:70, rede NET-3 ( │ │ │ │ │ │

net-tools * I:99 1016 config::net-tools net-tools, │ │ │ │ │ │

Page 313: Referências Debian

configuração de │ │ │ │ │ │

rede IPv4): │ │ │ │ │ │

ifconfig(8) etc.│ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

test network │ │ │ │ │ │

reachability of │ │ │ │ │ │

inetutils-ping * V:0.03, 296 test::net-tools a remote host by│ │ │ │ │ │

I:0.12 hostname or IP │ │ │ │ │ │

address (legacy,│ │ │ │ │ │

GNU) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

test network │ │ │ │ │ │

reachability of │ │ │ │ │ │

arping * V:0.5, 104 , , a remote host │ │ │ │ │ │

I:3 specified by the│ │ │ │ │ │

ARP address │ │ │ │ │ │

(legacy) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

rastreia o │ │ │ │ │ │

V:13, caminho de rede │ │ │ │ │ │

traceroute * I:99 192 , , até uma máquina │ │ │ │ │ │

remota (legacy, │ │ │ │ │ │

consola) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

dhcp3-client * V:32, 60 config::low-level Cliente DHCP │ │ │ │ │ │

I:92 │ │ │ │ │ │

Page 314: Referências Debian

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

suporte de │ │ │ │ │ │

wpasupplicant * V:28, 828 , , cliente para WPA│ │ │ │ │ │

I:39 e WPA2 (IEEE │ │ │ │ │ │

802.11i) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

ferramentas para│ │ │ │ │ │

V:7, manipular │ │ │ │ │ │

wireless-tools * I:22 420 , , Extensões │ │ │ │ │ │

Wireless do │ │ │ │ │ │

Linux │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

ppp * V:6, 1016 , , ligação PPP/ │ │ │ │ │ │

I:26 PPPoE com chat │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

ajudante de │ │ │ │ │ │

pppoeconf * V:0.4, 344 config::helper configuração │ │ │ │ │ │

I:3 para ligação │ │ │ │ │ │

PPPoE │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

ajudante de │ │ │ │ │ │

pppconfig * V:0.2, 964 , , configuração │ │ │ │ │ │

I:2 para ligação PPP│ │ │ │ │ │

com chat │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

Page 315: Referências Debian

ajudante de │ │ │ │ │ │

wvdial * V:0.5, 416 , , configuração │ │ │ │ │ │

I:2 para ligação PPP│ │ │ │ │ │

com wvdial e ppp│ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

rastreia o │ │ │ │ │ │

mtr-tiny * V:2, 120 test::low-level caminho de rede │ │ │ │ │ │

I:26 até uma máquina │ │ │ │ │ │

remota (curses) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

rastreia o │ │ │ │ │ │

V:0.7, caminho de rede │ │ │ │ │ │

mtr * I:3 180 , , até uma máquina │ │ │ │ │ │

remota (curses e│ │ │ │ │ │

GTK+) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

ferramentas para│ │ │ │ │ │

gnome-nettool * V:2, 2848 , , operações comuns│ │ │ │ │ │

I:33 de informação de│ │ │ │ │ │

rede (GNOME) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

mapeamento de │ │ │ │ │ │

nmap * V:6, 7112 , , rede / sondagem │ │ │ │ │ │

I:31 de portos (Nmap,│ │ │ │ │ │

consola) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

Page 316: Referências Debian

V:0.2, mapeamento de │ │ │ │ │ │

zenmap * I:1.3 2400 , , rede / sondagem │ │ │ │ │ │

de portos (GTK+)│ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

V:0.10, mapeamento de │ │ │ │ │ │

knmap * I:0.6 712 , , rede / sondagem │ │ │ │ │ │

de portos (KDE) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

analisador de │ │ │ │ │ │

tcpdump * V:3, 1020 , , tráfego de rede │ │ │ │ │ │

I:24 (Tcpdump, │ │ │ │ │ │

consola) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

analisador de │ │ │ │ │ │

wireshark * V:1.4, 2052 , , tráfego de rede │ │ │ │ │ │

I:9 (Wireshark, │ │ │ │ │ │

GTK+) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

V:0.4, analisador de │ │ │ │ │ │

tshark * I:3 276 , , tráfego de rede │ │ │ │ │ │

(consola) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

sistema de │ │ │ │ │ │

monitorização e │ │ │ │ │ │

nagios3 * V:1.0, 32 , , gestão para │ │ │ │ │ │

I:1.8 máquinas, │ │ │ │ │ │

Page 317: Referências Debian

serviços e redes│ │ │ │ │ │

(Nagios) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

produz um │ │ │ │ │ │

V:0.05, sumário das │ │ │ │ │ │

tcptrace * I:0.4 436 , , ligações a │ │ │ │ │ │

partir da saída │ │ │ │ │ │

do tcpdump │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

sistema flexível│ │ │ │ │ │

snort * V:0.6, 1260 , , de detecção de │ │ │ │ │ │

I:0.8 intrusos na rede│ │ │ │ │ │

(Snort) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

mostra a │ │ │ │ │ │

ntop * V:1.2, 11124 , , utilização da │ │ │ │ │ │

I:2 rede num │ │ │ │ │ │

navegador web │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

clientes de rede│ │ │ │ │ │

disponibilizados│ │ │ │ │ │

dnsutils * V:14, 412 , , com BIND: │ │ │ │ │ │

I:90 nslookup(8), │ │ │ │ │ │

nsupdate(8), dig│ │ │ │ │ │

(8) │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

Page 318: Referências Debian

check DNS zone │ │ │ │ │ │

dlint * V:0.4, 96 , , information │ │ │ │ │ │

I:6 using nameserver│ │ │ │ │ │

lookups │ │ │ │ │ │

├─────────────────────┼───────┼───────┼─────────────────┼────────────────┤

rastreia uma │ │ │ │ │ │

dnstracer * V:0.11, 92 , , cadeia de │ │ │ │ │ │

I:0.5 servidores DNS │ │ │ │ │ │

até à fonte │ │ │ │ │ │

└─────────────────────┴───────┴───────┴─────────────────┴────────────────┘

5.1.1. O nome de domínio

The naming for the domain name is a tricky one for the normal PC

workstation users. The PC workstation may be mobile one hopping

around the network or located behind the NAT firewall

inaccessible from the Internet. For such case, you may not want

the domain name to be a valid domain name to avoid name

collision.

Dica

When you use an invalid domain name, you need to spoof the

domain name used by some programs such as MTA for their proper

operation. See Secção 6.3.3, “A configuração do endereço de

mail”.

Page 319: Referências Debian

According to rfc2606, "invalid" seems to be a choice for the top

level domain (TLD) to construct domain names that are sure to be

invalid from the Internet.

The mDNS network discovery protocol (Apple Bonjour / Apple

Rendezvous, Avahi on Debian) uses "local" as the

pseudo-top-level domain. Microsoft also seems to promote "local"

for the TLD of local area network.

Atenção

If the DNS service on your LAN uses "local" as TLD for your LAN,

it may interfare with mDNS.

Other popular choices for the invalid TLD seem to be

"localdomain", "lan", "localnet", or "home" according to my

incoming mail analysis.

5.1.2. A resolução de nome de máquina

The hostname resolution is currently supported by the NSS (Name

Service Switch) mechanism too. The flow of this resolution is

the following.

1. The "/etc/nsswitch.conf" file with stanza like "hosts: files

dns" dictates the hostname resolution order. (This replaces

the old functionality of the "order" stanza in "/etc/

host.conf".)

2. The files method is invoked first. If the hostname is found

Page 320: Referências Debian

in the "/etc/hosts" file, it returns all valid addresses for

it and exits. (The "/etc/host.conf" file contains "multi

on".)

3. The dns method is invoked. If the hostname is found by the

query to the Internet Domain Name System (DNS) identified by

the "/etc/resolv.conf" file, it returns all valid addresses

for it and exits.

O ficheiro "/etc/hosts" que associa endereços IP com nomes de

máquinas contém o seguinte.

127.0.0.1 localhost

127.0.1.1 <host_name>.<domain_name> <host_name>

# As linhas seguintes são desejáveis para máquinas capazes de IPv6

::1 ip6-localhost ip6-loopback

fe00::0 ip6-localnet

ff00::0 ip6-mcastprefix

ff02::1 ip6-allnodes

ff02::2 ip6-allrouters

ff02::3 ip6-allhosts

Here the <host_name> in this matches the own hostname defined in

the "/etc/hostname". The <domain_name> in this is the fully

qualified domain name (FQDN) of this host.

Dica

For <domain_name> of the mobile PC without the real FQDN, you

Page 321: Referências Debian

may pick a bogus and safe TLD such as "lan", "home", "invalid",

"localdomain", "none", and "private".

The "/etc/resolv.conf" is a static file if the resolvconf

package is not installed. If installed, it is a symbolic link.

Either way, it contains information that initialize the resolver

routines. If the DNS is found at IP="192.168.11.1", it contains

the following.

nameserver 192.168.11.1

The resolvconf package makes this "/etc/resolv.conf" into a

symbolic link and manages its contents by the hook scripts

automatically.

The hostname resolution via Multicast DNS (using Zeroconf, aka

Apple Bonjour / Apple Rendezvous) which effectively allows name

resolution by common Unix/Linux programs in the ad-hoc mDNS

domain "local", can be provided by installing the libnss-mdns

package. The "/etc/nsswitch.conf" file should have stanza like

"hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4" to

enable this functionality.

5.1.3. O nome da interface de rede

The network interface name, e.g. eth0, is assigned to each

hardware in the Linux kernel through the user space

configuration mechanism, udev (see Secção 3.5.11, “O sistema

udev”), as it is found. The network interface name is referred

Page 322: Referências Debian

as physical interface in ifup(8) and interfaces(5).

In order to ensure each network interface to be named

persistently for each reboot using MAC address etc., there is a

record file "/etc/udev/rules.d/70-persistent-net.rules". This

file is automatically generated by the "/lib/udev/

write_net_rules" program, probably run by the

"persistent-net-generator.rules" rules file. You can modify it

to change naming rule.

Cuidado

When editing the "/etc/udev/rules.d/70-persistent-net.rules"

rules file, you must keep each rule on a single line and the MAC

address in lowercase. For example, if you find "Firewire device"

and "PCI device" in this file, you probably want to name "PCI

device" as eth0 and configure it as the primary network

interface.

5.1.4. O alcance de endereços de rede para a LAN

Let us be reminded of the IPv4 32 bit address ranges in each

class reserved for use on the local area networks (LANs) by

rfc1918. These addresses are guaranteed not to conflict with any

addresses on the Internet proper.

Tabela 5.2. Lista de alcances de endereços de rede

Page 323: Referências Debian

┌──────┬─────────────────┬─────────────┬─────────────┬─────────┐

Classe endereços de rede máscara de máscara de # de │ │ │ │ │ │

rede rede /bits sub-redes│ │ │ │ │ │

├──────┼─────────────────┼─────────────┼─────────────┼─────────┤

A 10.x.x.x 255.0.0.0 /8 1 │ │ │ │ │ │

├──────┼─────────────────┼─────────────┼─────────────┼─────────┤

B 172.16.x.x — 255.255.0.0 /16 16 │ │ │ │ │ │

172.31.x.x │ │ │ │ │ │

├──────┼─────────────────┼─────────────┼─────────────┼─────────┤

C 192.168.0.x — 255.255.255.0 /24 256 │ │ │ │ │ │

192.168.255.x │ │ │ │ │ │

└──────┴─────────────────┴─────────────┴─────────────┴─────────┘

Nota

If one of these addresses is assigned to a host, then that host

must not access the Internet directly but must access it through

a gateway that acts as a proxy for individual services or else

does Network Address Translation(NAT). The broadband router

usually performs NAT for the consumer LAN environment.

5.1.5. O suporte a dispositivos de rede

Although most hardware devices are supported by the Debian

system, there are some network devices which require DSFG

Page 324: Referências Debian

non-free external hardware drivers to support them. Please see

Secção 9.7.8, “Drivers de hardware não-livres”.

5.2. A configuração de rede moderna para desktop

Debian squeeze systems can manage the network connection via

management daemon software such as NetworkManager (NM)

(network-manager and associated packages) or Wicd (wicd and

associated packages).

Vêm com as suas próprias GUIs e programas de linha de●

comandos como as suas interfaces de utilizador.

Vêm com os seus próprios daemons como os seus sistemas de●

backend.

Permitem ligação fácil do seu sistema à Internet.●

Permitem gestão fácil de configuração de redes com fio e sem●

fios.

Permitem-nos configurar a rede independentemente do pacote●

legacy ifupdown.

Nota

Não use estas ferramentas de configuração de rede automáticas em

servidores. Estas são destinadas principalmente para os

utilizadores móveis em portáteis.

Estas ferramentas de configuração de rede modernas precisam de

ser configuradas correctamente para evitar entrarem em conflito

com o pacote legacy ifupdown e o seu ficheiro de configuração "/

Page 325: Referências Debian

etc/network/interfaces".

Nota

Some features of these automatic network configuration tools may

suffer regressions. These are not as robust as the legacy

ifupdown package. Check BTS of network-manager and BTS of wicd

for current issues and limitations.

5.2.1. Ferramentas GUI de configuração de rede

Official documentations for NM and Wicd on Debian are provided

in "/usr/share/doc/network-manager/README.Debian" and "/usr/

share/doc/wicd/README.Debian", respectively.

Essencialmente, a configuração de rede para desktop é feita como

se segue.

1. Make desktop user, e.g. foo, belong to group "netdev" by the

following (Alternatively, do it automatically via D-bus

under modern desktop environments such as GNOME and KDE).

$ sudo adduser foo netdev

2. Mantenha a configuração de "/etc/network/interfaces" tão

simples como o seguinte.

auto lo

iface lo inet loopback

Page 326: Referências Debian

3. Reiniciar NM ou Wicd com o seguinte.

$ sudo /etc/init.d/network-manager restart

$ sudo /etc/init.d/wicd restart

4. Configure a sua rede através de GUI.

Nota

Only interfaces which are not listed in "/etc/network/

interfaces" or which have been configured with "auto …" or

"allow-hotplug …" and "iface … inet dhcp" (with no other

options) are managed by NM to avoid conflict with ifupdown.

Dica

If you wish to extend network configuration capabilities of NM,

please seek appropriate plug-in modules and supplemental

packages such as network-manager-openconnect,

network-manager-openvpn-gnome, network-manager-pptp-gnome,

mobile-broadband-provider-info, gnome-bluetooth, etc. The same

goes for those of Wicd.

Cuidado

These automatic network configuration tools may not be

compatible with esoteric configurations of legacy ifupdown in "/

Page 327: Referências Debian

etc/network/interfaces" such as ones in Secção 5.5, “A

configuração de rede básica com ifupdown (legacy)” and

Secção 5.6, “A configuração de rede avançada com ifupdown

(legacy)”. Check BTS of network-manager and BTS of wicd for

current issues and limitations.

5.3. A ligação e configuração legacy de rede

When the method described in Secção 5.2, “A configuração de rede

moderna para desktop” does not suffice your needs, you should

use the legacy network connection and configuration method which

combines many simpler tools.

A ligação de rede legacy é específica para cada método (veja

Secção 5.4, “O método de ligação de rede (legacy)”).

Existem 2 tipos de programas para a configuração de rede de

baixo nível em Linux (veja Secção 5.7.1, “Comandos iproute2”).

Old net-tools programs (ifconfig(8), …) are from the Linux●

NET-3 networking system. Most of these are obsolete now.

New Linux iproute2 programs (ip(8), …) are the current Linux●

networking system.

Although these low level networking programs are powerful, they

are cumbersome to use. So high level network configuration

systems have been created.

The ifupdown package is the de facto standard for such high

Page 328: Referências Debian

level network configuration system on Debian. It enables you to

bring up network simply by doing , e.g., "ifup eth0". Its

configuration file is the "/etc/network/interfaces" file and its

typical contents are the following.

auto lo

iface lo inet loopback

auto eth0

iface eth0 inet dhcp

The resolvconf package was created to supplement ifupdown system

to support smooth reconfiguration of network address resolution

by automating rewrite of resolver configuration file "/etc/

resolv.conf". Now, most Debian network configuration packages

are modified to use resolvconf package (see "/usr/share/doc/

resolvconf/README.Debian").

Helper scripts to the ifupdown package such as ifplugd,

guessnet, ifscheme, etc. are created to automate dynamic

configuration of network environment such as one for mobile PC

on wired LAN. These are relatively difficult to use but play

well with existing ifupdown system.

These are explained in detail with examples (see Secção 5.5, “A

configuração de rede básica com ifupdown (legacy)” and

Secção 5.6, “A configuração de rede avançada com ifupdown

(legacy)”).

Page 329: Referências Debian

5.4. O método de ligação de rede (legacy)

Cuidado

The connection test method described in this section are meant

for testing purposes. It is not meant to be used directly for

the daily network connection. You are advised to use them via

NM, Wicd, or the ifupdown package (see Secção 5.2, “A

configuração de rede moderna para desktop” and Secção 5.5, “A

configuração de rede básica com ifupdown (legacy)”).

The typical network connection method and connection path for a

PC can be summarized as the following.

Tabela 5.3. Lista de métodos de ligação de rede e caminhos de

ligação

┌───────────┬──────────┬───────────────────────────────────────┐

PC método de caminho de ligação │ │ │ │

ligação │ │ │ │

├───────────┼──────────┼───────────────────────────────────────┤

Porto série PPP modem POTS ponto de acesso │ │ │⇔ ⇔ ⇔ │

(ppp0) dial-up ISP │ │ │ ⇔ │

├───────────┼──────────┼───────────────────────────────────────┤

Porto PPPoE/DHCP BB-modem serviço BB ponto de │ │ │⇔ ⇔ ⇔ │

Ethernet /Estático acesso BB ISP │ │ │ ⇔ │

(eth0) │ │ │ │

Page 330: Referências Debian

├───────────┼──────────┼───────────────────────────────────────┤

Porto DHCP/ LAN router BB com with tradução de │ │ │⇔ ⇔ │

Ethernet Estático endereços de rede (NAT) ( BB-modem …) │ │ │ ⇔ │

(eth0) │ │ │ │

└───────────┴──────────┴───────────────────────────────────────┘

Aqui está um sumário do script de configuração para cada método

de ligação.

Tabela 5.4. Lista de configurações de ligação de rede

┌──────────────┬─────────────────────────────────┬─────────────┐

método de configuração pacote(s) │ │ │ │

ligação backend │ │ │ │

├──────────────┼─────────────────────────────────┼─────────────┤

PPP pppconfig para criar conversa pppconfig, │ │ │ │

determinista ppp │ │ │ │

├──────────────┼─────────────────────────────────┼─────────────┤

PPP wvdialconf para criar conversa ppp, wvdial │ │ │ │

(alternativa) heurística │ │ │ │

├──────────────┼─────────────────────────────────┼─────────────┤

PPPoE pppoeconf para criar conversa pppoeconf, │ │ │ │

determinista ppp │ │ │ │

├──────────────┼─────────────────────────────────┼─────────────┤

Page 331: Referências Debian

DHCP descrito em "/etc/dhcp3/ dhcp3-client │ │ │ │

dhclient.conf" │ │ │ │

├──────────────┼─────────────────────────────────┼─────────────┤

IP estático descrito em "/etc/network/ net-tools │ │ │ │

(IPv4) interfaces" │ │ │ │

├──────────────┼─────────────────────────────────┼─────────────┤

IP estático descrito em "/etc/network/ iproute │ │ │ │

(IPv6) interfaces" │ │ │ │

└──────────────┴─────────────────────────────────┴─────────────┘

A ligação de rede anónima significa o seguinte.

Tabela 5.5. Lista de ligações de rede anónimas

┌────────┬─────────────────────────────────────────────────────┐

acrónimo significado │ │ │

├────────┼─────────────────────────────────────────────────────┤

POTS serviço de antigo telefone simples │ │ │

├────────┼─────────────────────────────────────────────────────┤

BB broadband │ │ │

├────────┼─────────────────────────────────────────────────────┤

serviço e.g., the digital subscriber line (DSL), the cable │ │ │

BB TV, or the fiber to the premises (FTTP) │ │ │

Page 332: Referências Debian

├────────┼─────────────────────────────────────────────────────┤

modem BB e.g., the DSL modem, the cable modem, or the optical │ │ │

network terminal (ONT) │ │ │

├────────┼─────────────────────────────────────────────────────┤

LAN rede de área local │ │ │

├────────┼─────────────────────────────────────────────────────┤

WAN rede de área alargada │ │ │

├────────┼─────────────────────────────────────────────────────┤

DHCP protocolo de configuração dinâmico de máquina │ │ │

├────────┼─────────────────────────────────────────────────────┤

PPP protocolo ponto-para-ponto │ │ │

├────────┼─────────────────────────────────────────────────────┤

PPPoE protocolo ponto-para-ponto sobre Ethernet │ │ │

├────────┼─────────────────────────────────────────────────────┤

ISP Provedor de serviço de Internet │ │ │

└────────┴─────────────────────────────────────────────────────┘

Nota

The WAN connection services via cable TV are generally served by

DHCP or PPPoE. The ones by ADSL and FTTP are generally served by

PPPoE. You have to consult your ISP for exact configuration

requirements of the WAN connection.

Page 333: Referências Debian

Nota

When BB-router is used to create home LAN environment, PCs on

LAN are connected to the WAN via BB-router with network address

translation (NAT). For such case, PC's network interfaces on the

LAN are served by static IP or DHCP from the BB-router.

BB-router must be configured to connect the WAN following the

instruction by your ISP.

5.4.1. A ligação DHCP com a Ethernet

The typical modern home and small business network, i.e. LAN,

are connected to the WAN(Internet) using some consumer grade

broadband router. The LAN behind this router is usually served

by the dynamic host configuration protocol (DHCP) server running

on the router.

Just install the dhcp3-client package for the Ethernet served by

the dynamic host configuration protocol (DHCP).

5.4.2. A ligação de IP estático com a Ethernet

Nenhuma acção especial necessária para a Ethernet servida pelo

IP estático.

5.4.3. A ligação PPP com o pppconfig

O script de configuração pppconfig configura a ligação PPP

Page 334: Referências Debian

interactivamente ao seleccionar o seguinte.

O número de telefone●

O nome de utilizador do ISP●

A palavra-passe do ISP●

A velocidade da porta●

A porta de comunicação do modem●

O método de autenticação●

Tabela 5.6. Lista de ficheiros de configuração para a ligação

PPP com pppconfig

┌────────────────┬─────────────────────────────────────────────┐

ficheiro função │ │ │

├────────────────┼─────────────────────────────────────────────┤

/etc/ppp/peers/ O ficheiro de configuração gerado pelo │ │ │

<nome_do_isp> pppconfig para um pppd específico para │ │ │

<nome_de_isp> │ │ │

├────────────────┼─────────────────────────────────────────────┤

/etc/chatscripts O ficheiro de configuração gerado pelo │ │ │

/<nome_do_isp> pppconfig para conversa especifica com │ │ │

<nome_de_isp> │ │ │

├────────────────┼─────────────────────────────────────────────┤

/etc/ppp/options O parâmetro de execução geral para o pppd │ │ │

├────────────────┼─────────────────────────────────────────────┤

/etc/ppp/ Dados de autenticação para PAP (risco de │ │ │

Page 335: Referências Debian

pap-secret segurança) │ │ │

├────────────────┼─────────────────────────────────────────────┤

/etc/ppp/ Dados de autenticação para CHAP (mais seguro)│ │ │

chap-secret │ │ │

└────────────────┴─────────────────────────────────────────────┘

Cuidado

The "<isp_name>" value of "provider" is assumed if pon and poff

commands are invoked without arguments.

Você pode testar a configuração usando ferramentas de

configuração de baixo nível como as seguintes.

$ sudo pon <nome_do_isp>

...

$ sudo poff <nome_do_isp>

Veja "/usr/share/doc/ppp/README.Debian.gz".

5.4.4. A ligação PPP alternativa com o wvdialconf

A different approach to using pppd(8) is to run it from wvdial

(1) which comes in the wvdial package. Instead of pppd running

chat(8) to dial in and negotiate the connection, wvdial does the

dialing and initial negotiating and then starts pppd to do the

rest.

Page 336: Referências Debian

O script de configuração wvdialconf configura a ligação PPP

interactivamente apenas ao seleccionar o seguinte.

O número de telefone●

O nome de utilizador do ISP●

A palavra-passe do ISP●

wvdial tem sucesso a criar a ligação na maioria dos casos e

mantêm uma lista de dados de autenticação automaticamente.

Tabela 5.7. Lista de ficheiros de configuração para a ligação

PPP com wvdialconf

┌────────────┬─────────────────────────────────────────────────┐

ficheiro função │ │ │

├────────────┼─────────────────────────────────────────────────┤

/etc/ppp/ O ficheiro de configuração gerado pelo wvdialconf│ │ │

peers/wvdial para o pppd específico para wvdial │ │ │

├────────────┼─────────────────────────────────────────────────┤

/etc/ O ficheiro de configuração gerado pelo wvdialconf│ │ │

wvdial.conf │ │ │

├────────────┼─────────────────────────────────────────────────┤

/etc/ppp/ O parâmetro de execução geral para o pppd │ │ │

options │ │ │

├────────────┼─────────────────────────────────────────────────┤

Page 337: Referências Debian

/etc/ppp/ Dados de autenticação para PAP (risco de │ │ │

pap-secret segurança) │ │ │

├────────────┼─────────────────────────────────────────────────┤

/etc/ppp/ Dados de autenticação para CHAP (mais seguro) │ │ │

chap-secret │ │ │

└────────────┴─────────────────────────────────────────────────┘

Você pode testar a configuração usando ferramentas de

configuração de baixo nível como as seguintes.

$ sudo wvdial

...

$ sudo killall wvdial

Veja wvdial(1) e wvdial.conf(5).

5.4.5. A ligação PPPoE com o pppoeconf

When your ISP serves you with PPPoE connection and you decide to

connect your PC directly to the WAN, the network of your PC must

be configured with the PPPoE. The PPPoE stand for PPP over

Ethernet. The configuration script pppoeconf configures the

PPPoE connection interactively.

Os ficheiros de configuração são o seguinte.

Tabela 5.8. Lista de ficheiros de configuração para a ligação

Page 338: Referências Debian

PPPoE com pppoeconf

┌───────────────┬──────────────────────────────────────────────┐

ficheiro função │ │ │

├───────────────┼──────────────────────────────────────────────┤

/etc/ppp/peers/ O ficheiro de configuração gerado pelo │ │ │

dsl-provider pppoeconf para o pppd específico para pppoe │ │ │

├───────────────┼──────────────────────────────────────────────┤

/etc/ppp/ O parâmetro de execução geral para o pppd │ │ │

options │ │ │

├───────────────┼──────────────────────────────────────────────┤

/etc/ppp/ Dados de autenticação para PAP (risco de │ │ │

pap-secret segurança) │ │ │

├───────────────┼──────────────────────────────────────────────┤

/etc/ppp/ Dados de autenticação para CHAP (mais seguro) │ │ │

chap-secret │ │ │

└───────────────┴──────────────────────────────────────────────┘

Você pode testar a configuração usando ferramentas de

configuração de baixo nível como as seguintes.

$ sudo /sbin/ifconfig eth0 up

$ sudo pon dsl-provider

...

Page 339: Referências Debian

$ sudo poff dsl-provider

$ sudo /sbin/ifconfig eth0 down

Veja "/usr/share/doc/pppoeconf/README.Debian".

5.5. A configuração de rede básica com ifupdown (legacy)

The traditional TCP/IP network setup on Debian system uses

ifupdown package as a high level tool. There are 2 typical

cases.

For dynamic IP system such as mobile PCs, you should setup●

TCP/IP network with the resolvconf package and enable you to

switch your network configuration easily (see Secção 5.5.4,

“A interface de rede servida por DHCP”).

For static IP system such as servers, you should setup TCP/●

IP network without the resolvconf package and keep your

system simple (see Secção 5.5.5, “A interface de rede com IP

estático”).

These traditional setup methods are quite useful if you wish to

set up advanced configuration (see Secção 5.5, “A configuração

de rede básica com ifupdown (legacy)”).

The ifupdown package provides the standardized framework for the

high level network configuration in the Debian system. In this

section, we learn the basic network configuration with ifupdown

with simplified introduction and many typical examples.

Page 340: Referências Debian

5.5.1. A sintaxe de comando simplificada

The ifupdown package contains 2 commands: ifup(8) and ifdown(8).

They offer high level network configuration dictated by the

configuration file "/etc/network/interfaces".

Tabela 5.9. Lista de comandos de configuração de rede básicos

com ifupdown

┌───────┬──────────────────────────────────────────────────────┐

comando acção │ │ │

├───────┼──────────────────────────────────────────────────────┤

ifup bring up a network interface eth0 with the │ │ │

eth0 configuration eth0 if "iface eth0" stanza exists │ │ │

├───────┼──────────────────────────────────────────────────────┤

ifdown bring down a network interface eth0 with the │ │ │

eth0 configuration eth0 if "iface eth0" stanza exists │ │ │

└───────┴──────────────────────────────────────────────────────┘

Atenção

Do not use low level configuration tools such as ifconfig(8) and

ip(8) commands to configure an interface in up state.

Nota

Page 341: Referências Debian

Não existe nenhum comando ifupdown.

5.5.2. A sintaxe básica de "/etc/network/interfaces"

The key syntax of "/etc/network/interfaces" as explained in

interfaces(5) can be summarized as the following.

Tabela 5.10. Lista de estrofes em "/etc/network/interfaces"

┌──────────────────────────┬───────────────────────────────────┐

estrofe significado │ │ │

├──────────────────────────┼───────────────────────────────────┤

inicia a interface │ │ │

"auto <nome_da_interface>" <nome_da_interface> no arranque do │ │ │

sistema │ │ │

├──────────────────────────┼───────────────────────────────────┤

"allow-auto , , │ │ │

<nome_de_interface>" │ │ │

├──────────────────────────┼───────────────────────────────────┤

"allow-hotplug start interface <interface_name> │ │ │

<nome_de_interface>" when the kernel detects a hotplug │ │ │

event from the interface │ │ │

├──────────────────────────┼───────────────────────────────────┤

Linhas começadas com definem a configuração de rede │ │ │

"iface <nome_de_configuração> │ │ │

<nome_de_configuração> …" │ │ │

Page 342: Referências Debian

├──────────────────────────┼───────────────────────────────────┤

Linhas iniciadas com define mapping value of │ │ │

"mapping <config_name> for the matching │ │ │

<nome_da_interface_global> <interface_name> │ │ │

" │ │ │

├──────────────────────────┼───────────────────────────────────┤

A linha começada com um ignore as comments (end-of-line │ │ │

cardinal "#" comments are not supported) │ │ │

├──────────────────────────┼───────────────────────────────────┤

Uma linha terminada com estende a configuração para a │ │ │

uma barra inversa "\" próxima linha │ │ │

└──────────────────────────┴───────────────────────────────────┘

Lines started with iface stanza has the following syntax.

iface <config_name> <address_family> <method_name>

<option1> <value1>

<option2> <value2>

...

For the basic configuration, the mapping stanza is not used and

you use the network interface name as the network configuration

name (See Secção 5.6.5, “A estrofe de mapeamento”).

Atenção

Page 343: Referências Debian

Do not define duplicates of the "iface" stanza for a network

interface in "/etc/network/interfaces".

5.5.3. A interface de rede loopback

The following configuration entry in the "/etc/network/

interfaces" file brings up the loopback network interface lo

upon booting the system (via auto stanza).

auto lo

iface lo inet loopback

This one always exists in the "/etc/network/interfaces" file.

5.5.4. A interface de rede servida por DHCP

After prepairing the system by Secção 5.4.1, “A ligação DHCP com

a Ethernet”, the network interface served by the DHCP is

configured by creating the configuration entry in the "/etc/

network/interfaces" file as the following.

allow-hotplug eth0

iface eth0 inet dhcp

hostname "minha_máquina"

When the Linux kernel detects the physical interface eth0, the

allow-hotplug stanza causes ifup to bring up the interface and

the iface stanza causes ifup to use DHCP to configure the

interface.

Page 344: Referências Debian

5.5.5. A interface de rede com IP estático

The network interface served by the static IP is configured by

creating the configuration entry in the "/etc/network/

interfaces" file as the following.

allow-hotplug eth0

iface eth0 inet static

address 192.168.11.100

netmask 255.255.255.0

broadcast 192.168.11.255

gateway 192.168.11.1

dns-domain lan

dns-nameservers 192.168.11.1

When the Linux kernel detects the physical interface eth0, the

allow-hotplug stanza causes ifup to bring up the interface and

the iface stanza causes ifup to use the static IP to configure

the interface.

Aqui, eu assumi o seguinte.

Alcance de endereços IP da rede LAN: 192.168.11.0 -●

192.168.11.255

Endereço IP da gateway: 192.168.11.1●

Endereço IP do PC: 192.168.11.100●

O pacote resolvconf: instalado●

O nome de domínio: "lan"●

Page 345: Referências Debian

Endereço IP do servidor DNS: 192.168.11.1●

When the resolvconf package is not installed, DNS related

configuration needs to be done manually by editing the "/etc/

resolv.conf" as the following.

nameserver 192.168.11.1

domain lan

Cuidado

The IP addresses used in the above example are not meant to be

copied literally. You have to adjust IP numbers to your actual

network configuration.

5.5.6. A base da interface LAN wireless

The wireless LAN (WLAN for short) provides the fast wireless

connectivity through the spread-spectrum communication of

unlicensed radio bands based on the set of standards called IEEE

802.11.

The WLAN interfaces are almost like normal Ethernet interfaces

but require some network ID and encryption key data to be

provided when they are initialized. Their high level network

tools are exactly the same as that of Ethernet interfaces except

interface names are a bit different like eth1, wlan0, ath0,

wifi0, … depending on the kernel drivers used.

Page 346: Referências Debian

Dica

The wmaster0 device is the master device which is an internal

device used only by SoftMAC with new mac80211 API of Linux.

Aqui estão algumas palavras chave para lembrar para a WLAN.

Tabela 5.11. Lista de siglas para WLAN

┌────────┬─────────────┬───────────────────────────────────────┐

acrónimo palavra significado │ │ │ │

completa │ │ │ │

├────────┼─────────────┼───────────────────────────────────────┤

NWID ID de rede 16 bit network ID used by pre-802.11 │ │ │ │

WaveLAN network (very deprecated) │ │ │ │

├────────┼─────────────┼───────────────────────────────────────┤

(Extended) network name of the Wireless Access │ │ │ │

(E)SSID Service Set Points (APs) interconnected to form an │ │ │ │

Identifier integrated 802.11 wireless LAN, Domain │ │ │ │

ID │ │ │ │

├────────┼─────────────┼───────────────────────────────────────┤

WEP, Wired 1st generation 64-bit (128-bit) │ │ │ │

(WEP2) Equivalent wireless encryption standard with │ │ │ │

Privacy 40-bit key (deprecated) │ │ │ │

├────────┼─────────────┼───────────────────────────────────────┤

Wi-Fi 2nd generation wireless encryption │ │ │ │

Page 347: Referências Debian

WPA Protected standard (most of 802.11i), compatible │ │ │ │

Access with WEP │ │ │ │

├────────┼─────────────┼───────────────────────────────────────┤

Wi-Fi 3rd generation wireless encryption │ │ │ │

WPA2 Protected standard (full 802.11i), non-compatible│ │ │ │

Access 2 with WEP │ │ │ │

└────────┴─────────────┴───────────────────────────────────────┘

The actual choice of protocol is usually limited by the wireless

router you deploy.

5.5.7. A interface LAN wireless com WPA/WPA2

You need to install the wpasupplicant package to support the

WLAN with the new WPA/WPA2.

In case of the DHCP served IP on WLAN connection, the "/etc/

network/interfaces" file entry should be as the following.

allow-hotplug ath0

iface ath0 inet dhcp

wpa-ssid homezone

# hexadecimal psk is encoded from a plaintext passphrase

wpa-psk 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f

Veja "/usr/share/doc/wpasupplicant/README.modes.gz".

Page 348: Referências Debian

5.5.8. A interface LAN wireless com WEP

You need to install the wireless-tools package to support the

WLAN with the old WEP. (Your consumer grade router may still be

using this insecure infrastructure but this is better than

nothing.)

Cuidado

Please note that your network traffic on WLAN with WEP may be

sniffed by others.

In case of the DHCP served IP on WLAN connection, the "/etc/

network/interfaces" file entry should be as the following.

allow-hotplug eth0

iface eth0 inet dhcp

wireless-essid Home

wireless-key1 0123-4567-89ab-cdef

wireless-key2 12345678

wireless-key3 s:password

wireless-defaultkey 2

wireless-keymode open

Veja "/usr/share/doc/wireless-tools/README.Debian".

5.5.9. A ligação PPP

Page 349: Referências Debian

You need to configure the PPP connection first as described

before (see Secção 5.4.3, “A ligação PPP com o pppconfig”).

Then, add the "/etc/network/interfaces" file entry for the

primary PPP device ppp0 as the following.

iface ppp0 inet ppp

provider <nome_do_isp>

5.5.10. A ligação PPP alternativa

You need to configure the alternative PPP connection with wvdial

first as described before (see Secção 5.4.4, “A ligação PPP

alternativa com o wvdialconf”). Then, add the "/etc/network/

interfaces" file entry for the primary PPP device ppp0 as the

following.

iface ppp0 inet wvdial

5.5.11. A ligação PPPoE

For PC connected directly to the WAN served by the PPPoE, you

need to configure system with the PPPoE connection as described

before (see Secção 5.4.5, “A ligação PPPoE com o pppoeconf”).

Then, add the "/etc/network/interfaces" file entry for the

primary PPPoE device eth0 as the following.

allow-hotplug eth0

iface eth0 inet manual

pre-up /sbin/ifconfig eth0 up

Page 350: Referências Debian

up ifup ppp0=dsl

down ifdown ppp0=dsl

post-down /sbin/ifconfig eth0 down

# O seguinte é usado apenas internamente

iface dsl inet ppp

provider dsl-provider

5.5.12. O estado de configuração de rede do ifupdown

The "/etc/network/run/ifstate" file stores the intended network

configuration states for all the currently active network

interfaces managed by the ifupdown package are listed.

Unfortunately, even if the ifupdown system fails to bring up the

interface as intended, the "/etc/network/run/ifstate" file lists

it active.

Unless the output of the ifconfig(8) command for an interface

does not have a line like following example, it can not be used

as a part of IPV4 network.

inet addr:192.168.11.2 Bcast:192.168.11.255 Mask:255.255.255.0

Nota

Para o dispositivo Ethernet ligado a PPPoE, ao resultado do

comando ifconfig(8) falta uma linha que se parece com o exemplo

em cima.

5.5.13. A base da configuração de rede

Page 351: Referências Debian

When you try to reconfigure the interface, e.g. eth0, you must

disable it first with the "sudo ifdown eth0" command. This

removes the entry of eth0 from the "/etc/network/run/ifstate"

file. (This may result in some error message if eth0 is not

active or it is configured improperly previously. So far, it

seems to be safe to do this for the simple single user work

station at any time.)

Agora você é livre de rescrever o conteúdo de "/etc/network/

interfaces" como necessitar para reconfigurar a interface de

rede eth0.

Então, você pode reactivar eth0 com o comando "sudo ifup eth0".

Dica

You can (re)initialize the network interface simply by "sudo

ifdown eth0;sudo ifup eth0".

5.5.14. O pacote ifupdown-extra

O pacote ifupdown-extra disponibiliza testes de ligação de rede

fáceis para usar com o pacote ifupdown.

O comando network-test(1) pode ser usado a partir da shell.●

Os scripts automáticos são corridos para cada execução do●

comando ifup.

Page 352: Referências Debian

O comando network-test poupa-lhe a trabalheira de executar

comandos de baixo nível para analisar o problema de rede.

Os scripts automáticos estão instalados em "/etc/network/*/" e

executam o seguinte.

Verificar a ligação de cabo de rede●

Verificar o uso duplicado de endereço IP●

Configura rotas estáticas do sistema baseadas na definição "●

/etc/network/routes"

Verificar se a gateway de rede está ao alcance●

Grava os resultados no ficheiro "/var/log/syslog"●

Este registo do syslog é bastante útil para administração de

problemas de rede no sistema remoto.

Dica

The automatic behavior of the ifupdown-extra package is

configurable with the "/etc/default/network-test". Some of these

automatic checks slow down the system boot-up a little bit since

it takes some time to listen for ARP replies.

5.6. A configuração de rede avançada com ifupdown (legacy)

A funcionalidade do pacote ifupdown pode ser melhorada para além

do que foi descrito em Secção 5.5, “A configuração de rede

básica com ifupdown (legacy)” com conhecimentos avançados.

Page 353: Referências Debian

As funcionalidades descritas aqui são completamente opcionais.

Estou a ser preguiçoso e minimalista, raramente me incomodo a

usar isto.

Cuidado

If you could not set up network connection by information in

Secção 5.5, “A configuração de rede básica com ifupdown (legacy)

”, you make situation worse by using information below.

5.6.1. O pacote ifplugd

The ifplugd package is older automatic network configuration

tool which can manage only Ethernet connections. This solves

unplugged/replugged Ethernet cable issues for mobile PC etc. If

you have NetworkManager or Wicd (see Secção 5.2, “A configuração

de rede moderna para desktop”) installed, you do not need this

package.

This package runs daemon and replaces auto or allow-hotplug

functionalities (see Tabela 5.10, “Lista de estrofes em "/etc/

network/interfaces"”) and starts interfaces upon their

connection to the network.

Aqui está como usar o pacote ifplugd para o porto Ethernet

interno, ex. eth0.

1. Remova a estrofe em "/etc/network/interfaces": "auto eth0"

ou "allow-hotplug eth0".

Page 354: Referências Debian

2. Mantenha a estrofe em "/etc/network/interfaces": "iface eth0

inet …" e "mapping …".

3. instale o pacote ifplugd.

4. Corra "sudo dpkg-reconfigure ifplugd".

5. Coloque eth0 como a "interface estática para ser

correspondida pelo ifplugd".

Agora, a configuração de rede funciona como deseja.

Após o ligar da máquina ou após a descoberta do hardware, a●

interface não é activada por si própria.

Processo de arranque rápido sem o longo tempo limite do○

DHCP.

No funny activated interface without proper IPv4 address○

(see Secção 5.5.12, “O estado de configuração de rede do

ifupdown”).

Após encontrar o cabo Ethernet, a interface é activada.●

Após algum tempo depois de desligar o cabo Ethernet, a●

interface é desactivada automaticamente.

Após ligar outro cabo Ethernet, a interface é activada sob o●

novo ambiente de rede.

Dica

Os argumentos para o comando ifplugd(8) podem definir o seu

comportamento tal como o atraso para reconfigurar interfaces.

5.6.2. O pacote ifmetric

Page 355: Referências Debian

O pacote ifmetric permite-nos manipular métricas de rotas à

posteriori mesmo para DHCP.

O seguinte configura a interface eth0 para ser preferida sobre a

interface wlan0.

1. Instale o pacote ifmetric.

2. Adicione uma linha de opção com "metric 0" logo por baixo da

linha "iface eth0 inet dhcp".

3. Adicione uma linha de opção com "metric 1" logo por baixo da

linha "iface wlan0 inet dhcp".

The metric 0 means the highest priority route and is the default

one. The larger metric value means lower priority routes. The IP

address of the active interface with the lowest metric value

becomes the originating one. See ifmetric(8).

5.6.3. A interface virtual

A single physical Ethernet interface can be configured as

multiple virtual interfaces with different IP addresses. Usually

the purpose is to connect an interface to several IP

subnetworks. For example, IP address based virtual web hosting

by a single network interface is one such application.

Por exemplo, vamos supor o seguinte.

A single Ethernet interface on your host is connected to a●

Page 356: Referências Debian

Ethernet hub (not to the broadband router).

O hub Ethernet esta ligado a ambos; Internet e rede LAN.●

A rede LAN usa a sub-rede 192.168.0.x/24.●

A sua máquina usa endereço IP servido por DHCP com a●

interface física eth0 para a Internet.

A sua máquina usa 192.168.0.1 com a interface virtual eth0:0●

para a LAN.

As seguintes estrofes em "/etc/network/interfaces" configuram a

sua rede.

iface eth0 inet dhcp

metric 0

iface eth0:0 inet static

address 192.168.0.1

netmask 255.255.255.0

network 192.168.0.0

broadcast 192.168.0.255

metric 1

Cuidado

Although this configuration example with network address

translation (NAT) using netfilter/iptables (see Secção 5.9,

“Infraestrutura do netfilter”) can provide cheap router for the

LAN with only single interface, there is no real firewall

capability with such set up. You should use 2 physical

interfaces with NAT to secure the local network from the

Internet.

Page 357: Referências Debian

5.6.4. A sintaxe de comando avançada

The ifupdown package offers advanced network configuration using

the network configuration name and the network interface name. I

use slightly different terminology from one used in ifup(8) and

interfaces(5).

Tabela 5.12. Lista de terminologia para dispositivos de rede

┌────────────┬────────────┬──────────────────────┬─────────────┐

terminologia a minha exemplos no texto descrição │ │ │ │ │

do manual terminologia seguinte │ │ │ │ │

├────────────┼────────────┼──────────────────────┼─────────────┤

nome dado │ │ │ │ │

nome da nome da pelo kernel │ │ │ │ │

interface interface de lo, eth0, do Linux │ │ │ │ │

física rede <nome_da_interface> (usando o │ │ │ │ │

mecanismo │ │ │ │ │

udev) │ │ │ │ │

├────────────┼────────────┼──────────────────────┼─────────────┤

testemunho de│ │ │ │ │

nome da nome da config1, config2, nome seguindo│ │ │ │ │

interface configuração <nome_da_configuração> iface no "/ │ │ │ │ │

lógica de rede etc/network/ │ │ │ │ │

interfaces" │ │ │ │ │

└────────────┴────────────┴──────────────────────┴─────────────┘

Page 358: Referências Debian

Basic network configuration commands in Secção 5.5.1, “A sintaxe

de comando simplificada” require the network configuration name

token of the iface stanza to match the network interface name in

the "/etc/network/interfaces".

Advanced network configuration commands enables separation of

the network configuration name and the network interface name in

the "/etc/network/interfaces" as the following.

Tabela 5.13. Lista de comandos avançados de configuração de rede

com ifupdown

┌───────────┬──────────────────────────────────────────────────┐

comando acção │ │ │

├───────────┼──────────────────────────────────────────────────┤

ifup eth0= torna activa a interface de rede eth0 com a │ │ │

config1 configuração config1 │ │ │

├───────────┼──────────────────────────────────────────────────┤

ifdown eth0 torna inactiva a interface de rede eth0 com a │ │ │

=config1 configuração config1 │ │ │

├───────────┼──────────────────────────────────────────────────┤

ifup eth0 bring up a network interface eth0 with the │ │ │

configuration selected by mapping stanza │ │ │

├───────────┼──────────────────────────────────────────────────┤

Page 359: Referências Debian

ifdown eth0 desactiva a interface de rede eth0 com a │ │ │

configuração seleccionada pela estrofe mapping │ │ │

└───────────┴──────────────────────────────────────────────────┘

5.6.5. A estrofe de mapeamento

We skipped explaining the mapping stanza in the "/etc/network/

interfaces" in Secção 5.5.2, “A sintaxe básica de "/etc/network/

interfaces"” to avoid complication. This stanza has the

following syntax.

mapping <interface_name_glob>

script <script_name>

map <script_input1>

map <script_input2>

map ...

This provides advanced feature to the "/etc/network/interfaces"

file by automating the choice of the configuration with the

mapping script specified by <script_name>.

Vamos seguir a execução do seguinte.

$ sudo ifup eth0

When the "<interface_name_glob>" matches "eth0", this execution

produces the execution of the following command to configure

Page 360: Referências Debian

eth0 automatically.

$ sudo ifup eth0=$(echo -e '<script_entrada1> \n <script_entrada2> \n ...' | <nome_do_script> eth0)

Aqui, as linhas de entrada do script com "map" são opcionais e

pode ser repetidas.

Nota

The glob for mapping stanza works like shell filename glob (see

Secção 1.5.6, “Glob da shell”).

5.6.6. A configuração de rede comutável manualmente

Here is how to switch manually among several network

configurations without rewriting the "/etc/network/interfaces"

file as in Secção 5.5.13, “A base da configuração de rede” .

Para todas as configurações de rede que precisa aceder, você

cria um único ficheiro "/etc/network/interfaces" como o

seguinte.

auto lo

iface lo inet loopback

iface config1 inet dhcp

hostname "mymachine"

Page 361: Referências Debian

iface config2 inet static

address 192.168.11.100

netmask 255.255.255.0

broadcast 192.168.11.255

gateway 192.168.11.1

dns-domain lan

dns-nameservers 192.168.11.1

iface pppoe inet manual

pre-up /sbin/ifconfig eth0 up

up ifup ppp0=dsl

down ifdown ppp0=dsl

post-down /sbin/ifconfig eth0 down

# O seguinte é usado apenas internamente

iface dsl inet ppp

provider dsl-provider

iface pots inet ppp

provider provider

Please note the network configuration name which is the token

after iface does not use the token for the network interface

name. Also, there are no auto stanza nor allow-hotplug stanza to

start the network interface eth0 automatically upon events.

Agora você está pronto para comutar a configuração de rede.

Let's move your PC to a LAN served by the DHCP. You bring up the

Page 362: Referências Debian

network interface (the physical interface) eth0 by assigning the

network configuration name (the logical interface name) config1

to it by the following.

$ sudo ifup eth0=config1

Password:

...

A interface eth0 está activa, configurada por DHCP e ligada a

LAN.

$ sudo ifdown eth0=config1

...

A interface eth0 está inactiva e desligada da LAN.

Vamos mover o seu PC para uma LAN servida por IP estático. Você

activa a interface de rede eth0 ao atribuir-lhe o nome de

configuração de rede config2 para ela com o seguinte.

$ sudo ifup eth0=config2

...

The interface eth0 is up, configured with static IP and

connected to LAN. The additional parameters given as dns-*

configures "/etc/resolv.conf" contents. This "/etc/resolv.conf"

is better manged if the resolvconf package is installed.

$ sudo ifdown eth0=config2

Page 363: Referências Debian

...

A interface eth0 está inactiva e desligada da LAN, outra vez.

Let's move your PC to a port on BB-modem connected to the PPPoE

served service. You bring up the network interface eth0 by

assigning the network configuration name pppoe to it by the

following.

$ sudo ifup eth0=pppoe

...

A interface eth0 está activa, configurada com ligação PPPoE

directamente ao ISP.

$ sudo ifdown eth0=pppoe

...

A interface eth0 está inactiva e desligada, outra vez.

Let's move your PC to a location without LAN or BB-modem but

with POTS and modem. You bring up the network interface ppp0 by

assigning the network configuration name pots to it by the

following.

$ sudo ifup ppp0=pots

...

A interface ppp0 está activa e ligada à Internet com PPP.

Page 364: Referências Debian

$ sudo ifdown ppp0=pots

...

A interface ppp0 está inactiva e desligada da Internet.

Você deve verificar o ficheiro "/etc/network/run/ifstate" para o

estado actual da configuração de rede do sistema ifupdown.

Atenção

Talvez precise de ajustar os números no final de eth*, ppp*,

etc. se possuir várias interfaces de rede.

5.6.7. Usar scripts com o sistema ifupdown

O sistema ifupdown corre automaticamente scripts instalados em "

/etc/network/*/" enquanto exporta variáveis de ambiente para os

scripts.

Tabela 5.14. Lista de variáveis de ambiente passadas pelo

sistema ifupdown

┌────────────┬─────────────────────────────────────────────────┐

variável de valor passado │ │ │

ambiente │ │ │

├────────────┼─────────────────────────────────────────────────┤

"$IFACE" nome físico (nome da interface) da interface a │ │ │

Page 365: Referências Debian

ser processada │ │ │

├────────────┼─────────────────────────────────────────────────┤

"$LOGICAL" nome lógico (nome da configuração) da interface a│ │ │

ser processada │ │ │

├────────────┼─────────────────────────────────────────────────┤

"$ADDRFAM" <família_de_endereços> da interface │ │ │

├────────────┼─────────────────────────────────────────────────┤

"$METHOD" <nome_de_método> da interface. (ex., "static") │ │ │

├────────────┼─────────────────────────────────────────────────┤

"$MODE" "start" if run from ifup, "stop" if run from │ │ │

ifdown │ │ │

├────────────┼─────────────────────────────────────────────────┤

as per "$MODE", but with finer granularity, │ │ │

"$PHASE" distinguishing the pre-up, post-up, pre-down and │ │ │

post-down phases │ │ │

├────────────┼─────────────────────────────────────────────────┤

"$VERBOSITY" indicates whether "--verbose" was used; set to 1 │ │ │

if so, 0 if not │ │ │

├────────────┼─────────────────────────────────────────────────┤

"$PATH" command search path: "/usr/local/sbin:/usr/local/│ │ │

bin:/usr/sbin:/usr/bin:/sbin:/bin" │ │ │

├────────────┼─────────────────────────────────────────────────┤

"$IF_ value for the corresponding option under the │ │ │

<OPTION>" iface stanza │ │ │

Page 366: Referências Debian

└────────────┴─────────────────────────────────────────────────┘

Here, each environment variable, "$IF_<OPTION>", is created from

the name for the corresponding option such as <option1> and

<option2> by prepending "$IF_", converting the case to the upper

case, replacing hyphens to underscores, and discarding

non-alphanumeric characters.

Dica

Veja Secção 5.5.2, “A sintaxe básica de "/etc/network/

interfaces"” para <família_de_endereços>, <nome_de_método>,

<opção1> e <opção2>

The ifupdown-extra package (see Secção 5.5.14, “O pacote

ifupdown-extra”) uses these environment variables to extend the

functionality of the ifupdown package. The ifmetric package (see

Secção 5.6.2, “O pacote ifmetric”) installs the "/etc/network/

if-up.d/ifmetric" script which sets the metric via the

"$IF_METRIC" variable. The guessnet package (see Secção 5.6.8,

“Mapeando com guessnet”), which provides simple and powerful

framework for the auto-selection of the network configuration

via the mapping mechanism, also uses these.

Nota

For more specific examples of custom network configuration

Page 367: Referências Debian

scripts using these environment variables, you should check

example scripts in "/usr/share/doc/ifupdown/examples/*" and

scripts used in ifscheme and ifupdown-scripts-zg2 packages.

These additional scripts have some overlaps of functionalities

with basic ifupdown-extra and guessnet packages. If you install

these additional scripts, you should customize these scripts to

avoid interferences.

5.6.8. Mapeando com guessnet

Instead of manually choosing configuration as described in

Secção 5.6.6, “A configuração de rede comutável manualmente”,

you can use the mapping mechanism described in Secção 5.6.5, “A

estrofe de mapeamento” to select network configuration

automatically with custom scripts.

The guessnet-ifupdown(8) command provided by the guessnet

package is designed to be used as a mapping script and provides

powerful framework to enhance the ifupdown system.

You list test condition as the value for guessnet options●

for each network configuration under iface stanza.

Mapping choses the iface with first non-ERROR result as the●

network configuration.

This dual usage of the "/etc/network/interfaces" file by the

mapping script, guessnet-ifupdown, and the original network

configuration infrastructure, ifupdown, does not cause negative

impacts since guessnet options only export extra environment

Page 368: Referências Debian

variables to scripts run by the ifupdown system. See details in

guessnet-ifupdown(8).

Nota

When multiple guessnet option lines are required in "/etc/

network/interfaces", use option lines started with guessnet1,

guessnet2, and so on, since the ifupdown package does not allow

starting strings of option lines to be repeated.

5.7. A configuração de rede de baixo nível

5.7.1. Comandos iproute2

Iproute2 commands offer complete low-level network configuration

capabilities. Here is a translation table from obsolete

net-tools commands to new iproute2 etc. commands.

Tabela 5.15. Tabela de tradução dos comandos obsoletos net-tools

para os novos comandos iproute2

┌─────────────────┬───────────┬────────────────────────────────┐

ferramentas de novo │ │ │ │

rede obsoletas iproute2 manipulação │ │ │ │

etc. │ │ │ │

├─────────────────┼───────────┼────────────────────────────────┤

ifconfig(8) ip addr endereço de protoco (IP ou IPv6)│ │ │ │

num dispositivo │ │ │ │

Page 369: Referências Debian

├─────────────────┼───────────┼────────────────────────────────┤

route(8) ip route entrada na tabela de rotas │ │ │ │

├─────────────────┼───────────┼────────────────────────────────┤

arp(8) ip neigh entrada na cache ARP ou NDISC │ │ │ │

├─────────────────┼───────────┼────────────────────────────────┤

ipmaddr ip maddr endereço multicast │ │ │ │

├─────────────────┼───────────┼────────────────────────────────┤

iptunnel ip tunnel túnel sobre IP │ │ │ │

├─────────────────┼───────────┼────────────────────────────────┤

nameif(8) ifrename(8) nomeia as interfaces de rede │ │ │ │

baseadas no endereço MAC │ │ │ │

├─────────────────┼───────────┼────────────────────────────────┤

mii-tool(8) ethtool(8) Definições de dispositivo │ │ │ │

Ethernet │ │ │ │

└─────────────────┴───────────┴────────────────────────────────┘

Veja ip(8) e Manual da Suite de Utilitários IPROUTE2.

5.7.2. Operações de rede seguras de baixo nível

Você pode usar comandos de rede de baixo nível como se segue em

segurança pois eles não mudam a configuração de rede.

Tabela 5.16. Lista de comandos de rede de baixo nível

Page 370: Referências Debian

┌──────────────────────┬───────────────────────────────────────┐

comando descrição │ │ │

├──────────────────────┼───────────────────────────────────────┤

ifconfig mostra o estado de ligação e endereço │ │ │

das interfaces activas │ │ │

├──────────────────────┼───────────────────────────────────────┤

ip addr show mostra o estado de ligação e endereço │ │ │

das interfaces activas │ │ │

├──────────────────────┼───────────────────────────────────────┤

route -n mostra toda a tabela de rotas em │ │ │

endereços numéricos │ │ │

├──────────────────────┼───────────────────────────────────────┤

ip route show mostra toda a tabela de rotas em │ │ │

endereços numéricos │ │ │

├──────────────────────┼───────────────────────────────────────┤

arp mostra o conteúdo actual das tabelas de│ │ │

cache ARP │ │ │

├──────────────────────┼───────────────────────────────────────┤

ip neigh mostra o conteúdo actual das tabelas de│ │ │

cache ARP │ │ │

├──────────────────────┼───────────────────────────────────────┤

plog mostra o log do daemon ppp │ │ │

├──────────────────────┼───────────────────────────────────────┤

Page 371: Referências Debian

ping yahoo.com verifica a ligação de Internet para │ │ │

"yahoo.com" │ │ │

├──────────────────────┼───────────────────────────────────────┤

whois yahoo.com verifica quem registou "yahoo.com" na │ │ │

base de dados de domínios │ │ │

├──────────────────────┼───────────────────────────────────────┤

traceroute yahoo.com rastreia a ligação Internet até │ │ │

"yahoo.com" │ │ │

├──────────────────────┼───────────────────────────────────────┤

tracepath yahoo.com rastreia a ligação Internet até │ │ │

"yahoo.com" │ │ │

├──────────────────────┼───────────────────────────────────────┤

mtr yahoo.com rastreia a ligação Internet até │ │ │

"yahoo.com" (repetidamente) │ │ │

├──────────────────────┼───────────────────────────────────────┤

dig [@dns-server.com] check DNS records of "example.com" by │ │ │

example.com [{a|mx| "dns-server.com" for a "a", "mx", or │ │ │

any}] "any" record │ │ │

├──────────────────────┼───────────────────────────────────────┤

iptables -L -n verifica o filtro de pacotes │ │ │

├──────────────────────┼───────────────────────────────────────┤

netstat -a procura todos os portos abertos │ │ │

├──────────────────────┼───────────────────────────────────────┤

netstat -l --inet procura portos a escutar │ │ │

Page 372: Referências Debian

├──────────────────────┼───────────────────────────────────────┤

netstat -ln --tcp procura portos TCP a escutar (numérico)│ │ │

├──────────────────────┼───────────────────────────────────────┤

dlint exemplo.com verifica a informação da zona DNS de │ │ │

"exemplo.com" │ │ │

└──────────────────────┴───────────────────────────────────────┘

Dica

Some of these low level network configuration tools reside in "/

sbin/". You may need to issue full command path such as "/sbin/

ifconfig" or add "/sbin" to the "$PATH" list in your "~

/.bashrc".

5.8. Optimização da rede

A optimização de rede genérica está para além do objectivo desta

documentação. Eu apenas toco em assuntos pertinentes às ligações

de grau de consumidor.

Tabela 5.17. Lista de ferramentas de optimização de rede

┌─────────┬───────┬───────┬────────────────────────────────────┐

pacotes popcon tamanho descrição │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

Page 373: Referências Debian

V:1.3, mostra informação da utilização de │ │ │ │ │

iftop * I:7 72 largura de banda numa interface de │ │ │ │ │

rede │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

iperf * V:0.5, 200 ferramenta de medição da largura de │ │ │ │ │

I:3 banda do Protocolo Internet │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

V:0.17, escreve um ficheiro "/etc/apt/ │ │ │ │ │

apt-spy * I:1.7 204 sources.list" baseado em testes de │ │ │ │ │

largura de banda │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

ifstat * V:0.2, 88 InterFace STATistics Monitoring │ │ │ │ │

I:1.2 │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

bmon * V:0.2, 188 monitor de largura de banda portável│ │ │ │ │

I:0.9 e estimador de taxas │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

ethstatus V:0.10, script que mede rapidamente a │ │ │ │ │

* I:0.7 84 transferência efectiva de um │ │ │ │ │

dispositivo de rede │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

bing * V:0.08, 96 testador de largura de banda │ │ │ │ │

I:0.6 empírica estocástica │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

bwm-ng * V:0.2, 152 monitor de largura de banda pequeno │ │ │ │ │

Page 374: Referências Debian

I:1.2 e simples baseado em consola │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

ethstats V:0.05, 52 monitor de estatísticas de Ethernet │ │ │ │ │

* I:0.3 baseado em consola │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

ipfm * V:0.04, 156 ferramenta de análise de largura de │ │ │ │ │

I:0.19 banda │ │ │ │ │

└─────────┴───────┴───────┴────────────────────────────────────┘

5.8.1. Encontrar o MTU óptimo

The Maximum Transmission Unit (MTU) value can be determined

experimentally with ping(8) with "-M do" option which sends ICMP

packets with data size starting from 1500 (with offset of 28

bytes for the IP+ICMP header) and finding the largest size

without IP fragmentation.

Por exemplo, tente o seguinte

$ ping -c 1 -s $((1500-28)) -M do www.debian.org

PING www.debian.org (194.109.137.218) 1472(1500) bytes of data.

From 192.168.11.2 icmp_seq=1 Frag needed and DF set (mtu = 1454)

--- www.debian.org ping statistics ---

0 packets transmitted, 0 received, +1 errors

Page 375: Referências Debian

Tente 1454 em vez de 1500

Você vê ping(8) com sucesso com 1454.

This process is Path MTU (PMTU) discovery (RFC1191) and the

tracepath(8) command can automate this.

Dica

The above example with PMTU value of 1454 is for my previous

FTTP provider which used Asynchronous Transfer Mode (ATM) as its

backbone network and served its clients with the PPPoE. The

actual PMTU value depends on your environment, e.g., 1500 for

the my new FTTP provider.

Tabela 5.18. Regras básicas para o valor MTU óptimo

┌────────────────────┬─────────────┬───────────────────────────┐

ambiente de rede MTU rationale │ │ │ │

├────────────────────┼─────────────┼───────────────────────────┤

Ligação Dial-up (IP: 576 standard │ │ │ │

PPP) │ │ │ │

├────────────────────┼─────────────┼───────────────────────────┤

Ligação Ethernet 1500 standard e predefinido │ │ │ │

(IP: DHCP ou fixo) │ │ │ │

├────────────────────┼─────────────┼───────────────────────────┤

Ligação Ethernet 1492 (= 2 bytes para o cabeçalho │ │ │ │

Page 376: Referências Debian

(IP: PPPoE) 1500-8) PPP e 6 bytes para o │ │ │ │

cabeçalho PPPoE │ │ │ │

├────────────────────┼─────────────┼───────────────────────────┤

Ethernet link (ISP's 1462 (= author's speculation: 18 │ │ │ │

backbone: ATM, IP: 48*31-18-8) for Ethernet header, 8 for │ │ │ │

DHCP or fixed) SAR trailer │ │ │ │

├────────────────────┼─────────────┼───────────────────────────┤

Ethernet link (ISP's see "Optimal MTU │ │ │ │

backbone: ATM, IP: 1454 (= configuration for PPPoE │ │ │ │

PPPoE) 48*31-8-18-8) ADSL Connections" for │ │ │ │

rationale │ │ │ │

└────────────────────┴─────────────┴───────────────────────────┘

Adicionalmente a estas regras básicas, você deve saber o

seguinte.

Any use of tunneling methods (VPN etc.) may reduce optimal●

MTU further by their overheads.

O valor MTU não deve exceder o valor PMTU determinado●

experimentalmente.

O maior valor MTU é geralmente melhor quando são conhecidas●

outras limitações.

5.8.2. Definir o MTU

Aqui estão exemplos para definir o valor MTU desde a sua

Page 377: Referências Debian

predefinição 1500 até 1454.

For the DHCP (see Secção 5.5.4, “A interface de rede servida por

DHCP”), you can replace pertinent iface stanza lines in the "/

etc/network/interfaces" with the following.

iface eth0 inet dhcp

hostname "minhamaquina"

pre-up /sbin/ifconfig $IFACE mtu 1454

For the static IP (see Secção 5.5.5, “A interface de rede com IP

estático”), you can replace pertinent 'iface' stanza lines in

the "/etc/network/interfaces" with the following.

iface eth0 inet static

address 192.168.11.100

netmask 255.255.255.0

broadcast 192.168.11.255

gateway 192.168.11.1

mtu 1454

dns-domain lan

dns-nameservers 192.168.11.1

Para o PPPoE directo (veja Secção 5.4.5, “A ligação PPPoE com o

pppoeconf”), você pode substituir a linha "mtu" pertinente no "/

etc/ppp/peers/dsl-provider" com o seguinte.

mtu 1454

Page 378: Referências Debian

O tamanho de segmento máximo (MSS) é usado como uma alternativa

ao tamanho do pacote. As relações entre MSS e MTU são as

seguintes.

MSS = MTU - 40 para IPv4●

MSS = MTU - 60 para IPv6●

Nota

The iptables(8) (see Secção 5.9, “Infraestrutura do netfilter”)

based optimization can clamp packet size by the MSS and is

useful for the router. See "TCPMSS" in iptables(8).

5.8.3. Optimização WAN TCP

The TCP throughput can be maximized by adjusting TCP buffer size

parameters as described in "TCP Tuning Guide" and "TCP tuning"

for the modern high-bandwidth and high-latency WAN. So far, the

current Debian default settings serve well even for my LAN

connected by the fast 1G bps FTTP service.

5.9. Infraestrutura do netfilter

Netfilter provides infrastructure for stateful firewall and

network address translation (NAT) with Linux kernel modules (see

Secção 3.5.12, “A inicialização de módulos do kernel”).

Tabela 5.19. Lista de ferramentas de firewall

Page 379: Referências Debian

┌───────────────┬───────┬───────┬──────────────────────────────┐

pacotes popcon tamanho descrição │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

iptables * V:27, 1316 ferramentas de administração │ │ │ │ │

I:99 para o netfilter │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

iptstate * V:0.14, 152 continuously monitor netfilter│ │ │ │ │

I:0.9 state (similar to top(1)) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

Shoreline Firewall, netfilter │ │ │ │ │

shorewall-perl V:0.15, 76 configuration file generator │ │ │ │ │

* I:0.5 (Perl-based, recommended for │ │ │ │ │

lenny) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

Shoreline Firewall, netfilter │ │ │ │ │

shorewall-shell I:1.9 76 configuration file generator │ │ │ │ │

* (shell-based, alternative for │ │ │ │ │

lenny) │ │ │ │ │

└───────────────┴───────┴───────┴──────────────────────────────┘

Main user space program of netfilter is iptables(8). You can

manually configure netfilter interactively from shell, save its

state with iptables-save(8), and restore it via init script with

iptables-restore(8) upon system reboot.

Page 380: Referências Debian

Scripts de ajuda de configuração como o shorewall facilitam este

processo.

Veja documentação em http://www.netfilter.org/documentation/ (ou

em "/usr/share/doc/iptables/html/").

Manual de Conceitos de Rede em Linux●

Manual do Packet Filtering em Linux 2.4●

Como Fazer NAT em Linux 2.4●

Dica

Apesar destes terem sido escritos para o Linux 2.4, ambos

comando iptables(8) e função de kernel netfilter aplicam-se ao

Linux 2.6 actual.

Capítulo 6. Aplicações de rede

Após estabelecer a ligação de rede (veja Capítulo 5,

Configuração de rede), você pode correr varias aplicações de

rede.

6.1. Exploradores web

Existem muitos pacotes de exploradores web para aceder a

conteúdos remotos com Hypertext Transfer Protocol (HTTP).

Tabela 6.1. Lista de exploradores web

Page 381: Referências Debian

┌────────────────┬──────┬───────┬────────┬─────────────────────┐

pacote popcon tamanho tipo descrição do │ │ │ │ │ │

explorador web │ │ │ │ │ │

├────────────────┼──────┼───────┼────────┼─────────────────────┤

iceweasel * V:30, 3761 X Mozilla Firefox sem │ │ │ │ │ │

I:48 marca │ │ │ │ │ │

├────────────────┼──────┼───────┼────────┼─────────────────────┤

Mozilla sem marca, │ │ │ │ │ │

iceape-browser * V:1.4, 35686 , , removido devido a │ │ │ │ │ │

I:2 questões de segurança│ │ │ │ │ │

bug#505565 │ │ │ │ │ │

├────────────────┼──────┼───────┼────────┼─────────────────────┤

epiphany-browser V:13, 1060 , , GNOME, HIG compliant,│ │ │ │ │ │

* I:34 Epiphany │ │ │ │ │ │

├────────────────┼──────┼───────┼────────┼─────────────────────┤

V:0.9, GNOME, Galeon, │ │ │ │ │ │

galeon * I:1.4 1776 , , substituído pelo │ │ │ │ │ │

Epiphany │ │ │ │ │ │

├────────────────┼──────┼───────┼────────┼─────────────────────┤

konqueror * V:8, 3584 , , KDE, Konqueror │ │ │ │ │ │

I:15 │ │ │ │ │ │

├────────────────┼──────┼───────┼────────┼─────────────────────┤

w3m * V:24, 1992 texto w3m │ │ │ │ │ │

I:84 │ │ │ │ │ │

Page 382: Referências Debian

├────────────────┼──────┼───────┼────────┼─────────────────────┤

lynx * I:22 252 , , Lynx │ │ │ │ │ │

├────────────────┼──────┼───────┼────────┼─────────────────────┤

elinks * V:2, 1448 , , ELinks │ │ │ │ │ │

I:5 │ │ │ │ │ │

├────────────────┼──────┼───────┼────────┼─────────────────────┤

links * V:3, 1380 , , Links (apenas texto) │ │ │ │ │ │

I:9 │ │ │ │ │ │

├────────────────┼──────┼───────┼────────┼─────────────────────┤

links2 * V:0.7, 3288 gráficos Links (gráficos de │ │ │ │ │ │

I:3 consola sem X) │ │ │ │ │ │

└────────────────┴──────┴───────┴────────┴─────────────────────┘

6.1.1. Configuração do explorador

Você poderá ser capaz de usar os seguintes strings especiais de

URL para alguns exploradores para confirmar as suas definições.

"about:"●

"about:config"●

"about:plugins"●

Debian offers many free browser plugin packages in the main

archive area which can handle not only Java (software platform)

and Flash but also MPEG, MPEG2, MPEG4, DivX, Windows Media Video

Page 383: Referências Debian

(.wmv), QuickTime (.mov), MP3 (.mp3), Ogg/Vorbis files, DVDs,

VCDs, etc. Debian also offers helper programs to install

non-free browser plugin packages as contrib or non-free archive

area.

Tabela 6.2. Lista de pacotes plugin de exploradores

┌────────────────────┬──────┬───────┬────────┬─────────────────┐

pacote popcon tamanho área descrição │ │ │ │ │ │

├────────────────────┼──────┼───────┼────────┼─────────────────┤

V:0.9, plugin de Java │ │ │ │ │ │

icedtea6-plugin * I:1.6 272 main baseado em │ │ │ │ │ │

OpenJDK e IcedTea│ │ │ │ │ │

├────────────────────┼──────┼───────┼────────┼─────────────────┤

plugin de Java │ │ │ │ │ │

sun-java6-plugin * I:10 100 non-free para o Java SE 6 │ │ │ │ │ │

da Sun (apenas │ │ │ │ │ │

i386) │ │ │ │ │ │

├────────────────────┼──────┼───────┼────────┼─────────────────┤

mozilla-plugin-gnash V:0.4, 60 main plugin de Flash │ │ │ │ │ │

* I:4 baseado no Gnash │ │ │ │ │ │

├────────────────────┼──────┼───────┼────────┼─────────────────┤

Ajudante de │ │ │ │ │ │

plugin de Flash │ │ │ │ │ │

flashplugin-nonfree V:1.3, para instalar o │ │ │ │ │ │

* I:15 132 contrib reprodutor de │ │ │ │ │ │

Page 384: Referências Debian

Flash da Adobe │ │ │ │ │ │

(apenas i386, │ │ │ │ │ │

amd64) │ │ │ │ │ │

├────────────────────┼──────┼───────┼────────┼─────────────────┤

Plugin de │ │ │ │ │ │

V:3, multimédia │ │ │ │ │ │

mozilla-plugin-vlc * I:4 128 main baseado no │ │ │ │ │ │

reprodutor de │ │ │ │ │ │

média VLC │ │ │ │ │ │

├────────────────────┼──────┼───────┼────────┼─────────────────┤

Plugin de │ │ │ │ │ │

multimédia │ │ │ │ │ │

totem-mozilla * V:20, 544 main baseado no │ │ │ │ │ │

I:34 reprodutor de │ │ │ │ │ │

média Totem do │ │ │ │ │ │

GNOME │ │ │ │ │ │

├────────────────────┼──────┼───────┼────────┼─────────────────┤

Plugin de │ │ │ │ │ │

gecko-mediaplayer * V:0.6, 724 main multimédia │ │ │ │ │ │

I:0.8 baseado no │ │ │ │ │ │

MPlayer (GNOME) │ │ │ │ │ │

├────────────────────┼──────┼───────┼────────┼─────────────────┤

Um wrapper para │ │ │ │ │ │

V:1.8, correr plugins │ │ │ │ │ │

nspluginwrapper * I:3 472 contrib i386 do Netscape │ │ │ │ │ │

em arquitectura │ │ │ │ │ │

amd64 │ │ │ │ │ │

Page 385: Referências Debian

└────────────────────┴──────┴───────┴────────┴─────────────────┘

Dica

Although use of above Debian packages are much easier, browser

plugins can be still manually enabled by installing "*.so" into

plugin directories (e.g., "/usr/lib/iceweasel/plugins/") and

restarting browsers.

Some web sites refuse to be connected based on the user-agent

string of your browser. You can work around this situation by

spoofing the user-agent string. For example, you can do this by

adding following line into user configuration files such as "~

/.gnome2/epiphany/mozilla/epiphany/user.js" or "~/.mozilla/

firefox/*.default/user.js".

user_pref{"general.useragent.override","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"};

Alternativamente, você pode adicionar ou reiniciar esta variável

ao escrever "about:config" no URL e clicar com o botão direito

no conteúdo mostrado.

Cuidado

Spoofed user-agent string may cause bad side effects with Java.

6.2. O sistema de mail (correio electrónico)

Page 386: Referências Debian

Cuidado

Se você está a configurar um servidor de mail para trocar mail

directamente com a Internet, deverá fazer melhor do que ler esta

documentação elementar.

Nota

Os exemplos seguintes de configuração são válidos apenas para a

estação de trabalho móvel típica em ligações de consumidor de

Internet.

6.2.1. Bases dos serviços de mail modernos

De modo a conter problemas de spam (correio não desejado nem

solicitado), muitos ISPs que disponibilizam as ligações à

Internet dos consumidores, estão a implementar contra medidas.

O serviço smarthost para os seus clientes enviarem mensagens●

usa o porto submissão de mensagem (587) especificado em

rfc4409 com a palavra-passe (serviço SMTP AUTH) especificada

em rfc4954.

As ligações SMTP no porto 25 a partir das suas máquinas de●

rede internas (excepto o servidor de saída de mail do

próprio ISP) para a Internet estão bloqueadas.

As ligações SMTP no porto 25 ao servidor de mail chegado do●

ISP a partir de algumas máquinas de redes externas suspeitas

estão bloqueadas. (As ligações a partir de máquinas na gama

Page 387: Referências Debian

de endereços IP dinâmicos usados pelo dial-up e outras

ligações de consumidores de Internet são as primeiras a

serem bloqueadas.)

Quando configurar o seu sistema de mail ou resolver problemas de

entrega de mail, você deve considerar estas novas limitações.

In light of these hostile Internet situation and limitations,

some independent Internet mail ISPs such as Yahoo.com and

Gmail.com offer the secure mail service which can be connected

from anywhere on the Internet using Transport Layer Security

(TLS) and its predecessor, Secure Sockets Layer (SSL).

The smarthost service for their customers to send message●

uses the SMTP/SSL port (465) or the message submission port

(587) with the password (SMTP AUTH service).

O mail de chegada está acessível no porto 995 TLS/POP3 com●

POP3.

Cuidado

It is not realistic to run SMTP server on consumer grade network

to send mail directly to the remote host reliably. They are very

likely to be rejected. You must use some smarthost services

offered by your connection ISP or independent mail ISPs. For the

simplicity, I assume that the smarthost is located at

"smtp.hostname.dom", requires SMTP AUTH, and uses the message

submission port (587) in the following text.

Page 388: Referências Debian

6.2.2. A estratégia de configuração de mail para estação de

trabalho

The most simple mail configuration is that the mail is sent to

the ISP's smarthost and received from ISP's POP3 server by the

MUA (see Secção 6.4, “Agente utilizador de mail (MUA)”) itself.

This type of configuration is popular with full featured GUI

based MUA such as icedove(1), evolution(1), etc. If you need to

filter mail by their types, you use MUA's filtering function.

For this case, the local MTA (see Secção 6.3, “Agente de

transporte de mail (MTA)”) need to do local delivery only.

The alternative mail configuration is that the mail is sent via

local MTA to the ISP's smarthost and received from ISP's POP3 by

the mail retriever (see Secção 6.5, “O adquiridor de mail remoto

e utilitário de reencaminhamento”) to the local mailbox. If you

need to filter mail by their types, you use MDA with filter (see

Secção 6.6, “Agente de entrega de mail (MDA) com filtro”) to

filter mail into separate mailboxes. This type of configuration

is popular with simple console based MUA such as mutt(1), gnus

(1), etc., although this is possible with any MUAs (see

Secção 6.4, “Agente utilizador de mail (MUA)”). For this case,

the local MTA (see Secção 6.3, “Agente de transporte de mail

(MTA)”) need to do both smarthost delivery and local delivery.

Since mobile workstation does not have valid FQDN, you must

configure the local MTA to hide and spoof the real local mail

name in outgoing mail to avoid mail delivery errors (see

Secção 6.3.3, “A configuração do endereço de mail”).

Page 389: Referências Debian

Dica

Você pode desejar configurar o MUA/MDA para usar Maildir para

armazenar as mensagens de email algures sob o seu directório

home.

6.3. Agente de transporte de mail (MTA)

Para uma estação de trabalho normal, a escolha popular para

Agente de Transporte de Mail (MTA) é ou o pacote exim4-* ou o

postfix. A escolha é sua.

Tabela 6.3. Lista de pacotes básicos relacionados com agente de

transporte de mail para estação de trabalho

┌──────────────────┬──────┬───────┬────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├──────────────────┼──────┼───────┼────────────────────────────┤

exim4-daemon-light V:60, Agente de transporte de mail│ │ │ │ │

* I:65 1104 Exim4 (MTA: predefinido em │ │ │ │ │

Debian) │ │ │ │ │

├──────────────────┼──────┼───────┼────────────────────────────┤

exim4-base * V:62, 1688 Documentação do Exim4 │ │ │ │ │

I:68 (texto) e ficheiros comuns │ │ │ │ │

├──────────────────┼──────┼───────┼────────────────────────────┤

exim4-doc-html * I:0.6 3440 Documentação do Exim4 (html)│ │ │ │ │

Page 390: Referências Debian

├──────────────────┼──────┼───────┼────────────────────────────┤

exim4-doc-info * I:0.3 556 Documentação do Exim4 (info)│ │ │ │ │

├──────────────────┼──────┼───────┼────────────────────────────┤

postfix * V:18, 3492 Agente de transporte de mail│ │ │ │ │

I:20 Postfix (MTA: alternativo) │ │ │ │ │

├──────────────────┼──────┼───────┼────────────────────────────┤

postfix-doc * I:1.9 3420 Documentação do Postfix │ │ │ │ │

(html+texto) │ │ │ │ │

├──────────────────┼──────┼───────┼────────────────────────────┤

V:2, Implementação Cyrus SASL API│ │ │ │ │

sasl2-bin * I:5 448 (postfix suplementar para │ │ │ │ │

SMTP AUTH) │ │ │ │ │

├──────────────────┼──────┼───────┼────────────────────────────┤

cyrus-sasl2-doc * I:2 284 Cyrus SASL - documentação │ │ │ │ │

└──────────────────┴──────┴───────┴────────────────────────────┘

Although the popcon vote count of exim4-* looks several times

popular than that of postfix, this does not mean postfix is not

popular with Debian developers. The Debian server system uses

both exim4 and postfix. The mail header analysis of mailing list

postings from prominent Debian developers also indicate both of

these MTAs are as popular.

The exim4-* packages are known to have very small memory

Page 391: Referências Debian

consumption and very flexible for its configuration. The postfix

package is known to be compact, fast, simple, and secure. Both

come with ample documentation and are as good in quality and

license.

Existem muitas escolhas para pacotes de agente de transporte de

mail (MTA) com capacidades e objectivos diferentes no arquivo

Debian.

Tabela 6.4. Lista de escolhas para pacotes de agente de

transporte de mail (MTA) no arquivo Debian.

┌──────────────────┬───────┬───────┬───────────────────────────┐

pacote popcon tamanho capacidade e focagem │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

exim4-daemon-light V:60, 1104 completo │ │ │ │ │

* I:65 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

postfix * V:18, 3492 completo (segurança) │ │ │ │ │

I:20 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

exim4-daemon-heavy V:1.7, 1220 completo (flexibilidade) │ │ │ │ │

* I:1.9 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

sendmail-bin * V:1.9, 2052 completo (apenas se você já│ │ │ │ │

I:2 está familiarizado) │ │ │ │ │

Page 392: Referências Debian

├──────────────────┼───────┼───────┼───────────────────────────┤

nullmailer * V:0.7, 436 nu, nenhum mail local │ │ │ │ │

I:0.8 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

ssmtp * V:1.2, 0 nu, nenhum mail local │ │ │ │ │

I:1.7 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

courier-mta * V:0.14, 12316 muito completo (interface │ │ │ │ │

I:0.15 web, etc.) │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

xmail * V:0.14, 836 leve │ │ │ │ │

I:0.16 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

masqmail * V:0.04, 624 leve │ │ │ │ │

I:0.05 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

esmtp * V:0.09, 172 leve │ │ │ │ │

I:0.2 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

V:0.07, leve (extensão de │ │ │ │ │

esmtp-run * I:0.11 64 compatibilidade do sendmail│ │ │ │ │

para esmtp) │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

msmtp * V:0.3, 340 leve │ │ │ │ │

Page 393: Referências Debian

I:0.8 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

V:0.11, leve (extensão de │ │ │ │ │

msmtp-mta * I:0.15 32 compatibilidade do sendmail│ │ │ │ │

para msmtp) │ │ │ │ │

└──────────────────┴───────┴───────┴───────────────────────────┘

6.3.1. A configuração do exim4

Para mail de Internet com smarthost, você (re)configura o pacote

exim4-* como o seguinte.

$ sudo /etc/init.d/exim4 stop

$ sudo dpkg-reconfigure exim4-config

Select "mail sent by smarthost; received via SMTP or fetchmail"

for "General type of mail configuration".

Set "System mail name:" to its default as the FQDN (see

Secção 5.1.2, “A resolução de nome de máquina”).

Set "IP-addresses to listen on for incoming SMTP connections:"

to its default as "127.0.0.1 ; ::1".

Unset contents of "Other destinations for which mail is

accepted:".

Page 394: Referências Debian

Unset contents of "Machines to relay mail for:".

Set "IP address or host name of the outgoing smarthost:" to

"smtp.hostname.dom:587".

Select "<No>" for "Hide local mail name in outgoing mail?". (Use

"/etc/email-addresses" as in Secção 6.3.3, “A configuração do

endereço de mail”, instead.)

Reply to "Keep number of DNS-queries minimal (Dial-on-Demand)?"

as one of the following.

"Não" se o sistema está ligado à Internet enquanto arranca.●

"Sim" se o sistema não está ligado à Internet enquanto●

arranca.

Defina o "Método de entrega para mail local:" para "formato mbox

em /var/mail".

Seleccione "<Sim>" para "Dividir configuração em pequenos

ficheiros?:".

Crie entradas de palavra-passe para o smarthost ao editar "/etc/

exim4/passwd.client".

$ sudo vim /etc/exim4/passwd.client

...

$ cat /etc/exim4/passwd.client

Page 395: Referências Debian

^smtp.*\.nome_de_máquina\.domínio:nome_de_máquina@nome_de_máquina.domínio:palavra-passe

Inicie o exim4 com o seguinte.

$ sudo /etc/init.d/exim4 start

o nome de máquina em "/etc/exim4/passwd.client" não deve ser o

alias. Você verifica o nome de máquina real com o seguinte.

$ host smtp.hostname.dom

smtp.hostname.dom é um alias para smtp99.hostname.dom.

smtp99.hostname.dom possui o endereço 123.234.123.89

Eu uso expressões regulares em "/etc/exim4/passwd.client" para

contornar o problema do alias. Provavelmente o SMTP AUTH

funciona mesmo que o ISP mova a máquina apontada pelo alias.

Cuidado

Você tem de executar update-exim4.conf(8) após actualizar

manualmente os ficheiros de configuração do exim4 em "/etc/exim4

/".

Cuidado

Starting exim4 takes long time if "No" (default value) was

chosen for the debconf query of "Keep number of DNS-queries

minimal (Dial-on-Demand)?" and the system is not connected to

Page 396: Referências Debian

the Internet while booting.

Nota

Por favor leia o guia oficial em "/usr/share/doc/exim4-base/

README.Debian.gz" e update-exim4.conf(8).

Dica

O ficheiro de personalização local "/etc/exim4/

exim4.conf.localmacros" pode ser criado para definir MACROs. Por

exemplo, o serviço de mail do Yahoo diz-se requerer

"MAIN_TLS_ENABLE = true" e "AUTH_CLIENT_ALLOW_NOTLS_PASSWORDS =

yes" nele.

Dica

If you are looking for a light weight MTA that respects "/etc/

aliases" for your laptop PC, you should consider to configure

exim4(8) with "QUEUERUNNER='queueonly'", "QUEUERUNNER=

'nodaemon'", etc. in "/etc/default/exim4".

6.3.2. A configuração do postfix com SASL

For the Internet mail via smarthost, you should first read

postfix documentation and key manual pages.

Tabela 6.5. Lista dos manuais importantes do postfix

Page 397: Referências Debian

┌────────────┬───────────────────────────────────────────────┐

comando função │ │ │

├────────────┼───────────────────────────────────────────────┤

postfix(1) Programa de controlo do postfix │ │ │

├────────────┼───────────────────────────────────────────────┤

postconf(1) Utilitário de configuração do postfix │ │ │

├────────────┼───────────────────────────────────────────────┤

postconf(5) Parâmetros de configuração do postfix │ │ │

├────────────┼───────────────────────────────────────────────┤

postmap(1) Manutenção da tabela de buscas do Postfix │ │ │

├────────────┼───────────────────────────────────────────────┤

postalias(1) Manutenção da base de dados de alias do Postfix│ │ │

└────────────┴───────────────────────────────────────────────┘

Você (re)configura os pacotes postfix e sasl2-bin como se segue.

$ sudo /etc/init.d/postfix stop

$ sudo dpkg-reconfigure postfix

Escolha "Internet com smarthost".

Defina "SMTP relay host (blank for none):" para "

[smtp.hostname.dom]:587" e configure-o como o seguinte.

Page 398: Referências Debian

$ sudo postconf -e 'smtp_sender_dependent_authentication = yes'

$ sudo postconf -e 'smtp_sasl_auth_enable = yes'

$ sudo postconf -e 'smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd'

$ sudo postconf -e 'smtp_sasl_type = cyrus'

$ sudo vim /etc/postfix/sasl_passwd

Crie entradas de palavra-passe para o smarthost.

$ cat /etc/postfix/sasl_passwd

[smtp.hostname.dom]:587 nome_utilizador:palavra_passe

$ sudo postmap hush:/etc/postfix/sasl_passwd

Arranque o postfix com o seguinte.

$ sudo /etc/init.d/postfix start

Here the use of "[" and "]" in the dpkg-reconfigure dialog and "

/etc/postfix/sasl_passwd" ensures not to check MX record but

directly use exact hostname specified. See "Enabling SASL

authentication in the Postfix SMTP client" in "usr/share/doc/

postfix/html/SASL_README.html".

6.3.3. A configuração do endereço de mail

There are a few mail address configuration files for mail

transport, delivery and user agents.

Tabela 6.6. Lista de ficheiros de configuração relacionados com

endereços de mail

Page 399: Referências Debian

┌───────────────┬──────────────┬───────────────────────────────┐

ficheiro função aplicação │ │ │ │

├───────────────┼──────────────┼───────────────────────────────┤

nome de │ │ │ │

máquina Específico de Debian, mailname │ │ │ │

/etc/mailname predefinido (5) │ │ │ │

para mail │ │ │ │

(saída) │ │ │ │

├───────────────┼──────────────┼───────────────────────────────┤

/etc/ host name ficheiros_de_configuração-exim4│ │ │ │

email-addresses spoofing for (5) específicos do exim(8) │ │ │ │

outgoing mail │ │ │ │

├───────────────┼──────────────┼───────────────────────────────┤

/etc/postfix/ host name específico do postfix(1), │ │ │ │

generic spoofing for activado após a execução do │ │ │ │

outgoing mail comando postmap(1). │ │ │ │

├───────────────┼──────────────┼───────────────────────────────┤

alias de nome geral, activado após a execução│ │ │ │

/etc/aliases de conta para do comando newaliases(1). │ │ │ │

mail recebido │ │ │ │

└───────────────┴──────────────┴───────────────────────────────┘

O mailname no ficheiro "/etc/mailname" é normalmente um nome de

Page 400: Referências Debian

domínio totalmente qualificado (FQDN) que resolve para um dos

endereços IP do anfitrião. Para a estação de trabalho móvel que

não tem um nome de máquina com endereço IP resolvível, regule

este mailname para o valor de "hostname -f". (Esta é uma escolha

segura e funciona para ambos exim4-* e postfix.)

Dica

O conteúdo de "/etc/mailname" é usado por muitos programas

não-MTA para o seu comportamento predefinido. Para o mutt,

defina as variáveis "hostname" e "from" no ficheiro ~/muttrc

para sobrepor o valor mailname. Para programas no pacote

devscripts, como o bts(1) e dch(1), exporte as variáveis de

ambiente "$DEBFULLNAME" e "$DEBEMAIL" para o sobrepor.

Dica

The popularity-contest package normally send mail from root

account with FQDN. You need to set MAILFROM in /etc/

popularity-contest.conf as described in the /usr/share/

popularity-contest/default.conf file. Otherwise, your mail will

be rejected by the smarthost SMTP server. Although this is

tedious, this approach is safer than rewriting the source

address for all mails from root by MTA and should be used for

other daemons and cron scripts.

Ao definir o mailname para "hostname -f", o spoofing do endereço

de mail da fonte via MTA pode ser realizado com o seguinte.

Page 401: Referências Debian

ficheiro "/etc/email-addresses" para exim4(8) como explicado●

em exim4-config_files(5)

ficheiro "/etc/postfix/generic" para postfix(1) como●

explicado no generic(5)

Para postfix, são necessários os seguintes passos extra.

# postmap hash:/etc/postfix/generic

# postconf -e 'smtp_generic_maps = hash:/etc/postfix/generic'

# postfix reload

Você pode testar a configuração do endereço de email usando o

seguinte.

exim(8) com as opções -brw, -bf, -bF, -bV, …●

postmap(1) com a opção -q●

Dica

O exim vem com vários programas utilitários como o exiqgrep(8) e

exipick(8). Veja "dpkg -L exim4-base|grep man8/" para os

comandos disponíveis.

6.3.4. Operações MTA básicas

Existem várias operações MTA básicas. Algumas podem ser

executadas via interface de compatibilidade do sendmail(1).

Tabela 6.7. Lista de operações MTA básicas

Page 402: Referências Debian

┌──────────┬──────────────────┬────────────────────────────────┐

comando comando postfix descrição │ │ │ │

exim │ │ │ │

├──────────┼──────────────────┼────────────────────────────────┤

sendmail sendmail lê mails da entrada standard e │ │ │ │

prepara a entrega (-bm) │ │ │ │

├──────────┼──────────────────┼────────────────────────────────┤

lista a lista de espera de mail │ │ │ │

mailq mailq com estado e ID de lista de │ │ │ │

espera (-bp) │ │ │ │

├──────────┼──────────────────┼────────────────────────────────┤

newaliases newaliases inicializa a base de dados e │ │ │ │

alias (-I) │ │ │ │

├──────────┼──────────────────┼────────────────────────────────┤

exim4 -q postqueue -f enxagua mails em espera (-q) │ │ │ │

├──────────┼──────────────────┼────────────────────────────────┤

postsuper -r ALL │ │ │ │

exim4 -qf deferred; enxagua todos mails │ │ │ │

postqueue -f │ │ │ │

├──────────┼──────────────────┼────────────────────────────────┤

exim4 -qff postsuper -r ALL; enxagua até mails congelados │ │ │ │

postqueue -f │ │ │ │

├──────────┼──────────────────┼────────────────────────────────┤

Page 403: Referências Debian

exim4 -Mg postsuper -h congela uma mensagem pelo seu ID│ │ │ │

queue_id queue_id de lista de espera │ │ │ │

├──────────┼──────────────────┼────────────────────────────────┤

exim4 -Mrm postsuper -d remove uma mensagem pelo seu ID │ │ │ │

queue_id queue_id de lista de espera │ │ │ │

├──────────┼──────────────────┼────────────────────────────────┤

N/D postsuper -d ALL remove todas as mensagens │ │ │ │

└──────────┴──────────────────┴────────────────────────────────┘

Dica

Poderá ser uma boa ideia enxaguar todos os mails por um script

em "/etc/ppp/ip-up.d/*".

6.4. Agente utilizador de mail (MUA)

If you subscribe to Debian related mailing list, it may be a

good idea to use such MUA as mutt and gnus which are the de

facto standard for the participant and known to behave as

expected.

Tabela 6.8. Lista de agentes utilizador de mail (MUA)

┌─────────┬───────┬───────┬────────────────────────────────────┐

pacote popcon tamanho tipo │ │ │ │ │

Page 404: Referências Debian

├─────────┼───────┼───────┼────────────────────────────────────┤

iceweasel V:30, 3761 Programa GUI X (sem marca Mozilla │ │ │ │ │

* I:48 Firefox) │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

evolution V:16, 4724 Programa GUI X (parte da suite │ │ │ │ │

* I:34 groupware) │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

icedove * V:8, 38864 Programa GUI X (sem marca Mozilla │ │ │ │ │

I:12 Thunderbird) │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

mutt * V:26, 6004 programa de terminal de caracteres │ │ │ │ │

I:83 provavelmente usado com o vim │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

gnus * V:0.06, 6453 programa de terminal de caracteres │ │ │ │ │

I:0.3 sob (x)emacs │ │ │ │ │

└─────────┴───────┴───────┴────────────────────────────────────┘

6.4.1. MUA básico — Mutt

Personalize "~/.muttrc" como se segue para usar o mutt como

agente de utilizador de mail (MUA) em combinação com o vim.

#

# User configuration file to override /etc/Muttrc

Page 405: Referências Debian

#

# spoof source mail address

set use_from

set hostname=example.dom

set from="Name Surname <[email protected]>"

set signature="~/.signature"

# vim: "gq" to reformat quotes

set editor="vim -c 'set tw=72 et ft=mail'"

# "mutt" goes to Inbox, while "mutt -y" lists mailboxes

set mbox_type=Maildir # use qmail Maildir format for creating mbox

set mbox=~/Mail # keep all mail boxes in $HOME/Mail/

set spoolfile=+Inbox # mail delivered to $HOME/Mail/Inbox

set record=+Outbox # save fcc mail to $HOME/Mail/Outbox

set postponed=+Postponed # keep postponed in $HOME/Mail/postponed

set move=no # do not move Inbox items to mbox

set quit=ask-yes # do not quit by "q" only

set delete=yes # always delete w/o asking while exiting

set fcc_clear # store fcc as non encrypted

# Mailboxes in Maildir (automatic update)

mailboxes `cd ~/Mail; /bin/ls -1|sed -e 's/^/+/' | tr "\n" " "`

unmailboxes Maillog *.ev-summary

## Default

#set index_format="%4C %Z %{%b %d} %-15.15L (%4l) %s"

## Thread index with senders (collapse)

set index_format="%4C %Z %{%b %d} %-15.15n %?M?(#%03M)&(%4l)? %s"

Page 406: Referências Debian

## Default

#set folder_format="%2C %t %N %F %2l %-8.8u %-8.8g %8s %d %f"

## just folder names

set folder_format="%2C %t %N %f"

Adicione o seguinte ao "/etc/mailcap" or "~/.mailcap" para

mostrar mail em HTML e anexos do MS Word 'inline'.

text/html; lynx -force_html %s; needsterminal;

application/msword; /usr/bin/antiword '%s'; copiousoutput; description="Microsoft Word Text"; nametemplate=%s.doc

Dica

O Mutt pode ser usado como o cliente IMAP e o conversor de

formato de mailbox. Você pode etiquetar as mensagens com "t",

"T", etc. Estas mensagens etiquetadas podem ser copiadas com ";

C" entre diferentes mailboxes e apagadas com ";d" numa acção

única.

6.5. O adquiridor de mail remoto e utilitário de

reencaminhamento

Apesar do fetchmail(1) ter sido o standard de facto para

adquiridor de mail remoto em GNU/Linux, o autor agora gosta do

getmail(1). Se você deseja rejeitar mail antes de o descarregar

para poupar largura de banda, o mailfilter ou o mpop podem ser

úteis. Independentemente de quais utilitários de adquirir mails

Page 407: Referências Debian

sejam usados, é boa ideia configurar o sistema para entregar os

mails adquiridos a um MDA, como o maildrop, via pipe.

Tabela 6.9. Lista de adquiridores de mail remoto e utilitários

de reencaminhamento

┌──────────┬───────┬───────┬───────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

fetchmail V:2, 2588 adquiridor de mail (POP3, APOP, │ │ │ │ │

* I:5 IMAP) (antigo) │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

V:0.3, adquiridor de mail (POP3, IMAP4, e │ │ │ │ │

getmail4 * I:0.9 668 SDPS) (simples, seguro e de │ │ │ │ │

confiança) │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

mailfilter V:0.00, adquiridor de mail (POP3) com │ │ │ │ │

* I:0.07 332 capacidade de filtragem por │ │ │ │ │

expressões regulares │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

mpop * V:0.01, 324 adquiridor de mail (POP3) e MDA com│ │ │ │ │

I:0.08 capacidade de filtragem │ │ │ │ │

└──────────┴───────┴───────┴───────────────────────────────────┘

Page 408: Referências Debian

6.5.1. configuração do getmail

A configuração do getmail(1) está descrita em documentação do

getmail.Aqui estão as minhas definições para aceder a múltiplas

contas POP3 como utilizador.

Crie "/usr/local/bin/getmails" como o seguinte.

#!/bin/sh

set -e

if [ -f $HOME/.getmail/running ]; then

echo "getmail já está a correr ... (se não, remova $HOME/.getmail/running)" >&2

pgrep -l "getmai[l]"

exit 1

else

echo "getmail não está a correr ... " >&2

fi

if [ -f $HOME/.getmail/stop ]; then

echo "não correr o getmail ... (se não, remova $HOME/.getmail/stop)" >&2

exit

fi

if [ "x$1" = "x-l" ]; then

exit

fi

rcfiles="/usr/bin/getmail"

for file in $HOME/.getmail/config/* ; do

rcfiles="$rcfiles --rcfile $file"

done

Page 409: Referências Debian

date -u > $HOME/.getmail/running

eval "$rcfiles $@"

rm $HOME/.getmail/running

Configure-o como o seguinte.

$ sudo chmod 755 /usr/local/bin/getmails

$ mkdir -m 0700 $HOME/.getmail

$ mkdir -m 0700 $HOME/.getmail/config

$ mkdir -m 0700 $HOME/.getmail/log

Crie ficheiros de configuração "$HOME/.getmail/config/pop3_name"

para cada conta POP3 como o seguinte.

[retriever]

type = SimplePOP3SSLRetriever

server = pop.exemplo.com

username = [email protected]

password = secreta

[destination]

type = MDA_external

path = /usr/bin/maildrop

unixfrom = True

[options]

verbose = 0

delete = True

delivered_to = False

Page 410: Referências Debian

message_log = ~/.getmail/log/pop3_name.log

Configure-o como o seguinte.

$ chmod 0600 $HOME/.getmail/config/*

Agenda o "/usr/local/bin/getmails" para correr a cada 15 minutos

com o cron(8) ao executar "sudo crontab -e -u

<nome_de_utilizador>" e adicionando o seguinte à entrada cron do

utilizador.

5,20,35,50 * * * * /usr/local/bin/getmails --quiet

Dica

Problems of POP3 access may not come from getmail. Some popular

free POP3 services may be violating the POP3 protocol and their

SPAM filter may not be perfect. For example, they may delete

messages just after receiving RETR command before receiving DELE

command and may quarantined messages into Spam mailbox. You

should minimize damages by configuring them to archive accessed

messages and not to delete them. See also "Some mail was not

downloaded".

6.5.2. configuração do fetchmail

fetchmail(1) configuration is set by "/etc/default/fetchmail", "

/etc/fetchmailrc" and "$HOME/.fetchmailrc". See its example in "

/usr/share/doc/fetchmail/examples/fetchmailrc.example".

Page 411: Referências Debian

6.6. Agente de entrega de mail (MDA) com filtro

A maioria dos programas MTA, como o postfix e exim4, funcionam

como MDA (mail delivery agent). Eles são MDAs especializados com

capacidades de filtragem.

Although procmail(1) has been de facto standard for MDA with

filter on GNU/Linux, author likes maildrop(1) now. Whichever

filtering utilities are used, it is good idea to configure

system to deliver filtered mails to a qmail-style Maildir.

Tabela 6.10. Lista de MDA com filtro

┌─────────┬──────────┬───────┬─────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├─────────┼──────────┼───────┼─────────────────────────────────┤

procmail V:19, I:84 368 MDA com filtro (antigo) │ │ │ │ │

* │ │ │ │ │

├─────────┼──────────┼───────┼─────────────────────────────────┤

mailagent V:0.3, I:5 1692 MDA com filtro Perl │ │ │ │ │

* │ │ │ │ │

├─────────┼──────────┼───────┼─────────────────────────────────┤

maildrop V:0.3, 1000 MDA com linguagem de filtragem │ │ │ │ │

* I:0.8 estruturada │ │ │ │ │

└─────────┴──────────┴───────┴─────────────────────────────────┘

Page 412: Referências Debian

6.6.1. configuração do maildrop

A configuração do maildrop(1) está descrita em documentação do

maildropfilter. Aqui está um exemplo de configuração para "$HOME

/.mailfilter".

# Local configuration

MAILROOT="$HOME/Mail"

# set this to /etc/mailname contents

MAILHOST="example.dom"

logfile $HOME/.maildroplog

# rules are made to override the earlier value by the later one.

# mailing list mails ?

if ( /^Precedence:.*list/:h || /^Precedence:.*bulk/:h )

{

# rules for mailing list mails

# default mailbox for mails from mailing list

MAILBOX="Inbox-list"

# default mailbox for mails from debian.org

if ( /^(Sender|Resent-From|Resent-Sender): .*debian.org/:h )

{

MAILBOX="service.debian.org"

}

# default mailbox for mails from bugs.debian.org (BTS)

if ( /^(Sender|Resent-From|Resent-sender): .*@bugs.debian.org/:h )

Page 413: Referências Debian

{

MAILBOX="bugs.debian.org"

}

# mailbox for each properly maintained mailing list with "List-Id: foo" or "List-Id: ...<foo.bar>"

if ( /^List-Id: ([^<]*<)?([^<>]*)>?/:h )

{

MAILBOX="$MATCH2"

}

}

else

{

# rules for non-mailing list mails

# default incoming box

MAILBOX="Inbox-unusual"

# local mails

if ( /Envelope-to: .*@$MAILHOST/:h )

{

MAILBOX="Inbox-local"

}

# html mails (99% spams)

if ( /DOCTYPE html/:b ||\

/^Content-Type: text\/html/ )

{

MAILBOX="Inbox-html"

}

# blacklist rule for spams

if ( /^X-Advertisement/:h ||\

/^Subject:.*BUSINESS PROPOSAL/:h ||\

Page 414: Referências Debian

/^Subject:.*URGENT.*ASISSTANCE/:h ||\

/^Subject: *I NEED YOUR ASSISTANCE/:h )

{

MAILBOX="Inbox-trash"

}

# whitelist rule for normal mails

if ( /^From: .*@debian.org/:h ||\

/^(Sender|Resent-From|Resent-Sender): .*debian.org/:h ||\

/^Subject: .*(debian|bug|PATCH)/:h )

{

MAILBOX="Inbox"

}

# whiltelist rule for BTS related mails

if ( /^Subject: .*Bug#.*/:h ||\

/^(To|Cc): .*@bugs.debian.org/:h )

{

MAILBOX="bugs.debian.org"

}

# whitelist rule for getmails cron mails

if ( /^Subject: Cron .*getmails/:h )

{

MAILBOX="Inbox-getmails"

}

}

# check existance of $MAILBOX

`test -d $MAILROOT/$MAILBOX`

if ( $RETURNCODE == 1 )

{

Page 415: Referências Debian

# create maildir mailbox for $MAILBOX

`maildirmake $MAILROOT/$MAILBOX`

}

# deliver to maildir $MAILBOX

to "$MAILROOT/$MAILBOX/"

exit

Atenção

Ao contrário do procmail, o maildrop não cria automaticamente os

directórios maildir em falta. Você tem de os criar manualmente

com antecedência usando o maildirmake(1) como no exemplo "$HOME

/.mailfilter".

6.6.2. configuração do procmail

Aqui está uma configuração semelhante com "$HOME/.procmailrc"

para procmail(1).

MAILDIR=$HOME/Maildir

DEFAULT=$MAILDIR/Inbox/

LOGFILE=$MAILDIR/Maillog

# sem dúvida mails com mau aspecto: despeja-os no lixo e termina

:0

* 1^0 ^X-Advertisement

* 1^0 ^Subject:.*BUSINESS PROPOSAL

* 1^0 ^Subject:.*URGENT.*ASISSTANCE

* 1^0 ^Subject: *I NEED YOUR ASSISTANCE

X-trash/

Page 416: Referências Debian

# Entrega de mensagens da lista de mail

:0

* 1^0 ^Precedence:.*list

* 1^0 ^Precedence:.*bulk

* 1^0 ^List-

* 1^0 ^X-Distribution:.*bulk

{

:0

* 1^0 ^Return-path:.*[email protected]

jp-debian-devel/

:0

* ^Resent-Sender.*[email protected]

debian-user/

:0

* ^Resent-Sender.*[email protected]

debian-devel/

:0

* ^Resent-Sender.*[email protected]

debian-announce

:0

mailing-list/

}

:0

Page 417: Referências Debian

Inbox/

6.6.3. Re-entregar o conteúdo da mbox

Você precisa de entregar manualmente os mails às caixas de

correio organizadas no seu directório home a partir de "/var/

mail/<nome_de_utilizador>" se o seu directório home ficar cheio

e o procmail(1) falhar. Após regular o espaço do disco no

directório home, corra o seguinte.

# /etc/init.d/${MAILDAEMON} stop

# formail -s procmail </var/mail/<nome_de_utilizador>

# /etc/init.d/${MAILDAEMON} start

6.7. Servidor POP3/IMAP4

Se você vai correr um servidor privado numa LAN, deve considerar

correr um servidor POP3 / IMAP4 para entregar mail aos clientes

da LAN.

Tabela 6.11. Lista de Servidores POP3/IMAP4

┌───────────────┬───────┬───────┬────┬─────────────────────────┐

pacote popcon tamanho tipo descrição │ │ │ │ │ │

├───────────────┼───────┼───────┼────┼─────────────────────────┤

qpopper * V:1.1, 636 POP3 Servidor POP3 Qualcomm │ │ │ │ │ │

I:4 avançado BSD │ │ │ │ │ │

Page 418: Referências Debian

├───────────────┼───────┼───────┼────┼─────────────────────────┤

V:1.6, Servidor de mail courier │ │ │ │ │ │

courier-pop * I:2 244 POP3 - Servidor POP3 (apenas │ │ │ │ │ │

formato maildir) │ │ │ │ │ │

├───────────────┼───────┼───────┼────┼─────────────────────────┤

V:0.10, O servidor POP2 e POP3 da│ │ │ │ │ │

ipopd * I:0.18 212 POP3 Universidade de │ │ │ │ │ │

Washington │ │ │ │ │ │

├───────────────┼───────┼───────┼────┼─────────────────────────┤

cyrus-pop3d-2.2 V:0.18, 852 POP3 Sistema de mail cyrus │ │ │ │ │ │

* I:0.3 (suporte de POP3) │ │ │ │ │ │

├───────────────┼───────┼───────┼────┼─────────────────────────┤

xmail * V:0.14, 836 POP3 Servidor de mail ESMTP/ │ │ │ │ │ │

I:0.16 POP3 │ │ │ │ │ │

├───────────────┼───────┼───────┼────┼─────────────────────────┤

V:2, Servidor de mail courier │ │ │ │ │ │

courier-imap * I:3 1624 IMAP - Servidor IMAP (apenas │ │ │ │ │ │

formato maildir) │ │ │ │ │ │

├───────────────┼───────┼───────┼────┼─────────────────────────┤

V:0.7, O servidor IMAP da │ │ │ │ │ │

uw-imapd * I:4 280 IMAP Universidade de │ │ │ │ │ │

Washington │ │ │ │ │ │

├───────────────┼───────┼───────┼────┼─────────────────────────┤

cyrus-imapd-2.2 V:0.4, 2632 IMAP Sistema de mail cyrus │ │ │ │ │ │

* I:0.6 (suporte de IMAP) │ │ │ │ │ │

Page 419: Referências Debian

└───────────────┴───────┴───────┴────┴─────────────────────────┘

6.8. O servidor de impressão e utilitário

No antigo sistema tipo Unix, o Line printer daemon do BSD era o

standard. Como o formato de impressão standard do software livre

é o PostScript nos sistemas tipo Unix, um sistema de filtragem

foi usado juntamente com o Ghostscript para activar a impressão

em impressoras não-PostScript.

Recentemente, o Common UNIX Printing System (CUPS) é o novo

standard de facto. O CUPS usa Internet Printing Protocol (IPP).

O IPP é agora suportado por outros SOs como o Windows XP e o Mac

OS X e tornou-se no novo standard de facto para várias

plataformas para impressão remota com capacidade de comunicação

bidireccional.

O formato de dados de impressão standard para a aplicação no

sistema Debian é o PostScript (PS) o qual é uma linguagem de

descrição de página. Os dados em formato PS são fornecidos ao

interpretador de PostScript Ghostscript para produzir os dados

de impressão específicos da impressora. Veja Secção 11.3.1,

“Ghostscript”.

Graças à funcionalidade de auto-conversão dependente do formato

de ficheiro do sistema CUPS, simplesmente fornecer quaisquer

dados ao comando lpr deverá gerar a saída de impressão esperada.

Page 420: Referências Debian

(No CUPS, o lpr pode ser activado ao instalar o pacote

cups-bsd.)

O sistema Debian tem alguns pacotes notáveis para os servidores

e utilitários de impressão.

Tabela 6.12. Lista de servidores de impressoras e utilitários

┌──────────────────────┬──────┬───────┬──────────┬─────────────┐

pacote popcon tamanho porto descrição │ │ │ │ │ │

├──────────────────────┼──────┼───────┼──────────┼─────────────┤

BSD lpr/lpd (│ │ │ │ │ │

lpr * V:2, 440 impressora daemon de │ │ │ │ │ │

I:2 (515) impressora de│ │ │ │ │ │

linha) │ │ │ │ │ │

├──────────────────────┼──────┼───────┼──────────┼─────────────┤

lprng * V:0.6, 2904 , , , , │ │ │ │ │ │

I:1.3 (Avançado) │ │ │ │ │ │

├──────────────────────┼──────┼───────┼──────────┼─────────────┤

V:33, Servidor CUPS│ │ │ │ │ │

cups * I:44 15540 IPP (631) de Impressão │ │ │ │ │ │

em Internet │ │ │ │ │ │

├──────────────────────┼──────┼───────┼──────────┼─────────────┤

Comandos de │ │ │ │ │ │

impressão do │ │ │ │ │ │

System V para│ │ │ │ │ │

Page 421: Referências Debian

o CUPS: lp │ │ │ │ │ │

V:17, (1), lpstat │ │ │ │ │ │

cups-client * I:46 908 , , (1), │ │ │ │ │ │

lpoptions(1),│ │ │ │ │ │

cancel(1), │ │ │ │ │ │

lpmove(8), │ │ │ │ │ │

lpinfo(8), │ │ │ │ │ │

lpadmin(8), …│ │ │ │ │ │

├──────────────────────┼──────┼───────┼──────────┼─────────────┤

comandos de │ │ │ │ │ │

impressão BSD│ │ │ │ │ │

cups-bsd * V:7, 420 , , para o CUPS: │ │ │ │ │ │

I:41 lpr(1), lpq │ │ │ │ │ │

(1), lprm(1),│ │ │ │ │ │

lpc(8) │ │ │ │ │ │

├──────────────────────┼──────┼───────┼──────────┼─────────────┤

cups-driver-gutenprint V:12, Não Drivers de │ │ │ │ │ │

* I:38 1212 aplicável impressoras │ │ │ │ │ │

para o CUPS │ │ │ │ │ │

└──────────────────────┴──────┴───────┴──────────┴─────────────┘

Dica

Você pode configurar o sistema CUPS ao apontar o seu explorador

web para "http://localhost:631/" .

Page 422: Referências Debian

6.9. O servidor de acesso remoto e utilitário (SSH)

O Secure SHell (SSH) é o modo seguro de efectuar ligações na

Internet. Uma versão livre do SSH chamada OpenSSH está

disponível nos pacotes openssh-client e openssh-server em

Debian.

Tabela 6.13. Lista de servidores de acesso remoto e utilitários

┌──────────────────────┬───────┬───────┬──────────────────────┬──────────┐

pacote popcon tamanho ferramenta descrição │ │ │ │ │ │

├──────────────────────┼───────┼───────┼──────────────────────┼──────────┤

V:52, Cliente de│ │ │ │ │ │

openssh-client * I:99 2104 ssh(1) shell │ │ │ │ │ │

segura │ │ │ │ │ │

├──────────────────────┼───────┼───────┼──────────────────────┼──────────┤

V:70, Servidor │ │ │ │ │ │

openssh-server * I:83 700 sshd(8) de shell │ │ │ │ │ │

segura │ │ │ │ │ │

├──────────────────────┼───────┼───────┼──────────────────────┼──────────┤

pede ao │ │ │ │ │ │

utilizador│ │ │ │ │ │

ssh-askpass-fullscreen V:0.08, 92 ssh-askpass-fullscreen uma frase │ │ │ │ │ │

* I:0.4 (1) passe para│ │ │ │ │ │

ssh-add │ │ │ │ │ │

(GNOME2) │ │ │ │ │ │

Page 423: Referências Debian

├──────────────────────┼───────┼───────┼──────────────────────┼──────────┤

pede ao │ │ │ │ │ │

utilizador│ │ │ │ │ │

ssh-askpass * V:0.7, 156 ssh-askpass(1) uma frase │ │ │ │ │ │

I:5 passe para│ │ │ │ │ │

ssh-add (X│ │ │ │ │ │

simples) │ │ │ │ │ │

└──────────────────────┴───────┴───────┴──────────────────────┴──────────┘

Cuidado

Veja Secção 4.7.3, “Medidas de segurança extra para a Internet”

se o seu SSH for acessível a partir da Internet.

Dica

Por favor use o programa screen(1) para activar a sobrevivência

do processo de shell remota à interrupção da ligação (veja

Secção 9.1, “O programa screen”).

6.9.1. Bases do SSH

Atenção

o "/etc/ssh/sshd_not_to_be_run" não pode estar presente se

desejar correr o servidor OpenSSH.

Page 424: Referências Debian

SSH tem dois protocolos de autenticação.

Tabela 6.14. Lista de protocolos e métodos de autenticação do

SSH

┌─────────┬─────────────────────────────────┬──────────────────┐

Protocolo Método SSH descrição │ │ │ │

SSH │ │ │ │

├─────────┼─────────────────────────────────┼──────────────────┤

autenticação de │ │ │ │

SSH-1 "RSAAuthentication" utilizador baseada│ │ │ │

em chave de │ │ │ │

identificação RSA │ │ │ │

├─────────┼─────────────────────────────────┼──────────────────┤

autenticação │ │ │ │

baseada em │ │ │ │

, , "RhostsAuthentication" ".rhosts" │ │ │ │

(insegura, │ │ │ │

desactivada) │ │ │ │

├─────────┼─────────────────────────────────┼──────────────────┤

autenticação de │ │ │ │

máquina baseada em│ │ │ │

, , "RhostsRSAAuthentication" ".rhosts" │ │ │ │

combinada com │ │ │ │

chave de máquina │ │ │ │

RSA (desactivada) │ │ │ │

Page 425: Referências Debian

├─────────┼─────────────────────────────────┼──────────────────┤

autenticação │ │ │ │

, , "ChallengeResponseAuthentication" challenge-response│ │ │ │

RSA │ │ │ │

├─────────┼─────────────────────────────────┼──────────────────┤

autenticação │ │ │ │

, , "PasswordAuthentication" baseada em │ │ │ │

palavra-passe │ │ │ │

├─────────┼─────────────────────────────────┼──────────────────┤

autenticação do │ │ │ │

SSH-2 "PubkeyAuthentication" utilizador baseada│ │ │ │

em chave pública │ │ │ │

├─────────┼─────────────────────────────────┼──────────────────┤

autenticação de │ │ │ │

máquina baseada em│ │ │ │

"~/.rhosts" ou "/ │ │ │ │

etc/hosts.equiv" │ │ │ │

, , "HostbasedAuthentication" combinada com │ │ │ │

chave pública de │ │ │ │

autenticação da │ │ │ │

máquina cliente │ │ │ │

(desactivada) │ │ │ │

├─────────┼─────────────────────────────────┼──────────────────┤

, , "ChallengeResponseAuthentication" autenticação │ │ │ │

challenge-response│ │ │ │

Page 426: Referências Debian

├─────────┼─────────────────────────────────┼──────────────────┤

autenticação │ │ │ │

, , "PasswordAuthentication" baseada em │ │ │ │

palavra-passe │ │ │ │

└─────────┴─────────────────────────────────┴──────────────────┘

Cuidado

Tenha cuidado com estas diferenças se você não estiver a usar um

sistema Debian.

Veja "/usr/share/doc/ssh/README.Debian.gz", ssh(1), sshd(8),

ssh-agent(1), e ssh-keygen(1) para detalhes.

Os ficheiros de configuração chave são os seguintes.

Tabela 6.15. Lista de ficheiros de configuração do SSH

┌───────────────┬──────────────────────────────────────────────┐

ficheiro de descrição do ficheiro de configuração │ │ │

configuração │ │ │

├───────────────┼──────────────────────────────────────────────┤

/etc/ssh/ Predefinições do cliente SSH, veja ssh_config │ │ │

ssh_config (5) │ │ │

├───────────────┼──────────────────────────────────────────────┤

Page 427: Referências Debian

/etc/ssh/ Predefinições do sevidor SSH, veja sshd_config│ │ │

sshd_config (5) │ │ │

├───────────────┼──────────────────────────────────────────────┤

~/.ssh/ chaves SSH públicas predefinidas que os │ │ │

authorized_keys clientes usam para ligar a esta conta neste │ │ │

servidor SSH │ │ │

├───────────────┼──────────────────────────────────────────────┤

~/.ssh/identity chave SSH-1 RSA secreta do utilizador │ │ │

├───────────────┼──────────────────────────────────────────────┤

~/.ssh/id_rsa chave SSH-2 RSA secreta do utilizador │ │ │

├───────────────┼──────────────────────────────────────────────┤

~/.ssh/id_dsa chave SSH-2 DSA secreta do utilizador │ │ │

└───────────────┴──────────────────────────────────────────────┘

Dica

Veja ssh-keygen(1), ssh-add(1) e ssh-agent(1) para como usar

chaves SSH secretas e públicas.

Dica

Certifique-se de verificar as configurações ao testar a ligação.

Em caso de problemas, use "ssh -v".

Dica

Page 428: Referências Debian

Você pode mudar a frase-passe para encriptar chaves SSH secretas

locais mais tarde com "ssh-keygen -p".

Dica

Você pode adicionar opções às entradas em "~/.ssh/

authorized_keys" para limitar máquinas e correr comandos

específicos. Veja sshd(8) para mais detalhes.

O seguinte inicia uma ligação ssh(1) a partir de um cliente.

Tabela 6.16. Lista de exemplos de arranque do cliente SSH

┌───────────────────────────────────────┬──────────────────────┐

comando descrição │ │ │

├───────────────────────────────────────┼──────────────────────┤

ssh ligar com modo │ │ │

nome_utilizador@máquina.domínio.externo predefinido │ │ │

├───────────────────────────────────────┼──────────────────────┤

ssh -v ligar com modo │ │ │

nome_utilizador@máquina.domínio.externo predefinido com │ │ │

mensagens de depuração│ │ │

├───────────────────────────────────────┼──────────────────────┤

ssh -1 força a ligação com │ │ │

nome_utilizador@máquina.domínio.externo SSH versão 1 │ │ │

Page 429: Referências Debian

├───────────────────────────────────────┼──────────────────────┤

ssh -1 -o RSAAuthentication=no -l força o uso de │ │ │

nome_utilizador máquina.domínio.externo palavra-passe com SSH │ │ │

versão 1 │ │ │

├───────────────────────────────────────┼──────────────────────┤

ssh -o PreferredAuthentications= força o uso de │ │ │

password -l nome_utilizador palavra-passe com SSH │ │ │

máquina.domínio.externo versão 2 │ │ │

└───────────────────────────────────────┴──────────────────────┘

If you use the same user name on the local and the remote host,

you can eliminate typing "username@". Even if you use different

user name on the local and the remote host, you can eliminate it

using "~/.ssh/config". For Debian Alioth service with account

name "foo-guest", you set "~/.ssh/config" to contain the

following.

Host alioth.debian.org svn.debian.org git.debian.org

User foo-guest

For the user, ssh(1) functions as a smarter and more secure

telnet(1). Unlike telnet command, ssh command does not bomb on

the telnet escape character (initial default CTRL-]).

6.9.2. Reencaminhamento de portos para SMTP/POP3 em túnel

Page 430: Referências Debian

To establish a pipe to connect to port 25 of remote-server from

port 4025 of localhost, and to port 110 of remote-server from

port 4110 of localhost through ssh, execute on the local host as

the following.

# ssh -q -L 4025:remote-server:25 4110:remote-server:110 username@remote-server

This is a secure way to make connections to SMTP/POP3 servers

over the Internet. Set the "AllowTcpForwarding" entry to "yes"

in "/etc/ssh/sshd_config" of the remote host.

6.9.3. Ligar sem palavras-passe remotas

One can avoid having to remember passwords for remote systems by

using "RSAAuthentication" (SSH-1 protocol) or

"PubkeyAuthentication" (SSH-2 protocol).

On the remote system, set the respective entries,

"RSAAuthentication yes" or "PubkeyAuthentication yes", in "/etc/

ssh/sshd_config".

Crie chaves de autenticação localmente e instale a chave pública

no sistema remoto como o seguinte.

"RSAAuthentication": chave RSA para SSH-1 (descontinuado●

porque foi substituído.)

$ ssh-keygen

Page 431: Referências Debian

$ cat .ssh/identity.pub | ssh utilizador1@remoto "cat - >>.ssh/authorized_keys"

"PubkeyAuthentication": chave RSA para SSH-2●

$ ssh-keygen -t rsa

$ cat .ssh/id_rsa.pub | ssh utilizador1@remoto "cat - >>.ssh/authorized_keys"

"PubkeyAuthentication": chave DSA para SSH-2 (descontinuado●

porque é lento.)

$ ssh-keygen -t dsa

$ cat .ssh/id_dsa.pub | ssh utilizador1@remoto "cat - >>.ssh/authorized_keys"

Dica

Use of DSA key for SSH-2 is deprecated because key is smaller

and slow. There are no more reasons to work around RSA patent

using DSA since it has been expired. DSA stands for Digital

Signature Algorithm and slow. Also see DSA-1571-1.

Nota

For "HostbasedAuthentication" to work in SSH-2, you must adjust

the settings of "HostbasedAuthentication" to "yes" in both "/etc

/ssh/sshd_config" on the server host and "/etc/ssh/ssh_config"

or "~/.ssh/config" on the client host.

6.9.4. Lidar com clientes SSH alienígenas

Page 432: Referências Debian

Existem alguns clientes SSH livres disponíveis para outras

plataformas.

Tabela 6.17. Lista de clientes SSH para outras plataformas

┌─────────────┬────────────────────────────────────────────────┐

ambiente programa de SSH livre │ │ │

├─────────────┼────────────────────────────────────────────────┤

Windows puTTY (http://www.chiark.greenend.org.uk/ │ │ │

~sgtatham/putty/) (GPL) │ │ │

├─────────────┼────────────────────────────────────────────────┤

Windows SSH em cygwin (http://www.cygwin.com/) (GPL) │ │ │

(cygwin) │ │ │

├─────────────┼────────────────────────────────────────────────┤

Macintosh macSSH (http://www.macssh.com/) (GPL) │ │ │

Clássico │ │ │

├─────────────┼────────────────────────────────────────────────┤

Mac OS X OpenSSH; use ssh na aplicação de Terminal (GPL) │ │ │

└─────────────┴────────────────────────────────────────────────┘

6.9.5. Configurar o ssh-agent

É mais seguro proteger as suas chaves secretas de autenticação

SSH com uma frase-passe. Se nenhuma frase-passe foi definida,

Page 433: Referências Debian

use "ssh-keygen -p" para a definir.

Coloque a sua chave SSH pública (ex. "~/.ssh/id_rsa.pub") em "~

/.ssh/authorized_keys" numa máquina remota usando uma ligação à

máquina remota baseada em palavra-passe como descrito em cima.

$ ssh-agent bash

$ ssh-add ~/.ssh/id_rsa

Insira frase-passe para /home/<nome_de_utilizador>/.ssh/id_rsa:

Identidade adicionada: /home/<nome_de_utilizador>/.ssh/id_rsa (/home/<nome_de_utilizador>/.ssh/id_rsa)

Nenhuma palavra-passe necessária desde aqui até ao próximo

comando.

$ scp foo <nome_utilizador>@máquina.remota:foo

Carregue em ^D (CTRL-D) para terminar a sessão do ssh-agent.

For the X server, the normal Debian startup script executes

ssh-agent as the parent process. So you only need to execute

ssh-add once. For more, read ssh-agent(1)and ssh-add(1).

6.9.6. Como desligar o sistema remoto em SSH

You need to protect the process doing "shutdown -h now" (see

Secção 1.1.8, “Como desligar o sistema”) from the termination of

SSH using the at(1) command (see Secção 9.5.13, “Scheduling

tasks once”) by the following.

Page 434: Referências Debian

# echo "shutdown -h now" | at now

Correr "shutdown -h now" numa sessão do screen(1) (veja

Secção 9.1, “O programa screen”) é outro modo de fazer o mesmo.

6.9.7. Depurar problemas no SSH

Se estiver com problemas, verifique as permissões dos ficheiros

de configuração e corra o ssh com a opção "-v".

Use a opção "-P" se você for o root e esteja a ter problemas com

a firewall; isto evita o uso dos portos de servidor 1 -- 1023.

If ssh connections to a remote site suddenly stop working, it

may be the result of tinkering by the sysadmin, most likely a

change in "host_key" during system maintenance. After making

sure this is the case and nobody is trying to fake the remote

host by some clever hack, one can regain a connection by

removing the "host_key" entry from "~/.ssh/known_hosts" on the

local host.

6.10. Outras aplicações de servidor de rede

Aqui estão outras aplicações de servidor de rede

Tabela 6.18. Lista de outras aplicações de servidor de rede

Page 435: Referências Debian

┌───────────────────┬───────┬───────┬─────────┬────────────────┐

pacote popcon tamanho protocolo descrição │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

telnetd * V:0.4, 156 TELNET Servidor TELNET │ │ │ │ │ │

I:1.1 │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

telnetd-ssl * V:0.10, 152 , , . . (suporte a │ │ │ │ │ │

I:0.3 SSL) │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

V:12, Partilha de │ │ │ │ │ │

nfs-kernel-server * I:21 412 NFS ficheiros do │ │ │ │ │ │

Unix │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

Partilha de │ │ │ │ │ │

samba * V:18, 23096 SMB ficheiros e │ │ │ │ │ │

I:31 impressoras do │ │ │ │ │ │

Windows │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

Partilha de │ │ │ │ │ │

V:5, ficheiros e │ │ │ │ │ │

netatalk * I:9 3428 ATP impressoras do │ │ │ │ │ │

Apple/Mac │ │ │ │ │ │

(AppleTalk) │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

proftpd-basic * V:6, 4064 FTP Download de │ │ │ │ │ │

Page 436: Referências Debian

I:7 ficheiros geral │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

wu-ftpd * V:0.4, 820 , , , , │ │ │ │ │ │

I:0.6 │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

apache2-mpm-prefork V:38, 68 HTTP Servidor web │ │ │ │ │ │

* I:42 geral │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

apache2-mpm-worker V:6, 68 , , , , │ │ │ │ │ │

* I:7 │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

squid * V:6, 1848 , , servidor proxy │ │ │ │ │ │

I:7 web geral │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

squid3 * V:1.5, 3600 , , , , │ │ │ │ │ │

I:1.8 │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

V:0.14, Servidor OpenSLP│ │ │ │ │ │

slpd * I:0.2 180 SLP como servidor │ │ │ │ │ │

LDAP │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

bind9 * V:10, 1080 DNS Endereço IP para│ │ │ │ │ │

I:17 outras máquinas │ │ │ │ │ │

├───────────────────┼───────┼───────┼─────────┼────────────────┤

Page 437: Referências Debian

dhcp3-server * V:5, 64 DHCP Endereço IP do │ │ │ │ │ │

I:10 próprio cliente │ │ │ │ │ │

└───────────────────┴───────┴───────┴─────────┴────────────────┘

Common Internet File System Protocol (CIFS) é o mesmo protocolo

que Server Message Block (SMB) e é bastante usado pelo Microsoft

Windows.

Dica

Use of proxy server such as squid is much more efficient for

saving bandwidth than use of local mirror server with the full

Debian archive contents.

6.11. Outros clientes de aplicação de rede

Aqui estão outros clientes de aplicação de rede.

Tabela 6.19. Lista de clientes de aplicação de rede

┌────────────┬──────┬───────┬─────────┬────────────────────────┐

pacote popcon tamanho protocolo descrição │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

netcat * I:28 36 TCP/IP Canivete suíço do TCP/IP│ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

Binário Secure Socket │ │ │ │ │ │

Page 438: Referências Debian

V:56, Layer (SSL) e │ │ │ │ │ │

openssl * I:91 2380 SSL ferramentas │ │ │ │ │ │

criptográficas │ │ │ │ │ │

relacionadas │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

stunnel4 * V:0.6, 512 , , Wrapper SSL universal │ │ │ │ │ │

I:2 │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

telnet * V:13, 200 TELNET Cliente TELNET │ │ │ │ │ │

I:89 │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

telnet-ssl * V:0.2, 208 , , . . (suporte a SSL) │ │ │ │ │ │

I:1.1 │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

nfs-common * V:49, 660 NFS Partilha de ficheiros do│ │ │ │ │ │

I:81 Unix │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

V:6, Cliente de partilha de │ │ │ │ │ │

smbclient * I:35 45200 SMB ficheiros e impressoras │ │ │ │ │ │

do MS Windows │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

V:5, Comandos de montar e │ │ │ │ │ │

smbfs * I:24 56 , , desmontar para ficheiros│ │ │ │ │ │

remotos do MS Windows │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

Page 439: Referências Debian

ftp * V:9, 168 FTP Cliente FTP │ │ │ │ │ │

I:85 │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

lftp * V:1.3, 1876 , , , , │ │ │ │ │ │

I:6 │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

ncftp * V:1.4, 1276 , , Cliente FTP de écran │ │ │ │ │ │

I:7 completo │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

wget * V:33, 2364 HTTP e downloader de web │ │ │ │ │ │

I:99 FTP │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

curl * V:7, 352 , , , , │ │ │ │ │ │

I:23 │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

bind9-host * V:43, 188 DNS host(1) do bind9, │ │ │ │ │ │

I:91 "Prioridade: standard" │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

dnsutils * V:14, 412 , , dig(1) do bind, │ │ │ │ │ │

I:90 "Prioridade: standard" │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

dhcp3-client V:32, 60 DHCP obter endereço IP │ │ │ │ │ │

* I:92 │ │ │ │ │ │

├────────────┼──────┼───────┼─────────┼────────────────────────┤

Page 440: Referências Debian

ldap-utils * V:2, 672 LDAP obter dados de um │ │ │ │ │ │

I:7 servidor LDAP │ │ │ │ │ │

└────────────┴──────┴───────┴─────────┴────────────────────────┘

6.12. Os diagnósticos dos daemons do sistema

O programa telnet activa ligação manual aos daemons do sistema e

aos seus diagnósticos.

Para testar o serviço POP3 simples, tente o seguinte:

$ telnet mail.ispname.net pop3

Para testar o serviço POP3 com TLS/SSL activo de alguns ISPs,

você precisa do cliente telnet com TLS/SSL activo pelos pacotes

telnet-ssl or openssl.

$ telnet -z ssl pop.gmail.com 995

$ openssl s_client -connect pop.gmail.com:995

Os seguintes RFCs disponibilizam o conhecimento necessário para

cada daemon de sistema.

Tabela 6.20. Lista de RFCs populares

┌─────────────────┬────────────────────────────────────────────┐

Page 441: Referências Debian

RFC descrição │ │ │

├─────────────────┼────────────────────────────────────────────┤

rfc1939 e rfc2449 serviço POP3 │ │ │

├─────────────────┼────────────────────────────────────────────┤

rfc3501 serviço IMAP4 │ │ │

├─────────────────┼────────────────────────────────────────────┤

rfc2821 (rfc821) serviço SMTP │ │ │

├─────────────────┼────────────────────────────────────────────┤

rfc2822 (rfc822) Formato de ficheiro de mail │ │ │

├─────────────────┼────────────────────────────────────────────┤

rfc2045 Multipurpose Internet Mail Extensions (MIME)│ │ │

├─────────────────┼────────────────────────────────────────────┤

rfc819 serviço DNS │ │ │

├─────────────────┼────────────────────────────────────────────┤

rfc2616 serviço HTTP │ │ │

├─────────────────┼────────────────────────────────────────────┤

rfc2396 definição URI │ │ │

└─────────────────┴────────────────────────────────────────────┘

A utilização de portos é descrita em "/etc/services".

Capítulo 7. O Sistema X Window

Page 442: Referências Debian

O Sistema X Window no sistema Debian é baseado na fonte do X.Org

. Até Julho de 2009, eles são X11R7.1(etch), X11R7.3(lenny),

X11R7.3(squeeze) e X11R7.4(sid).

7.1. Pacotes chave

Existem alguns (meta)pacotes disponibilizados para facilitar a

instalação.

Tabela 7.1. Lista de (meta)pacotes chave para o X Window

┌─────────────────────────┬──────┬───────┬─────────────────────┐

(meta)pacote popcon tamanho descrição │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

bibliotecas do X, um │ │ │ │ │

servidor X, um │ │ │ │ │

conjunto de fonts e │ │ │ │ │

xorg * I:43 80 um grupo de clientes │ │ │ │ │

X básicos e │ │ │ │ │

utilitários │ │ │ │ │

(meta-pacote) │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

V:30, conjuntos completos │ │ │ │ │

xserver-xorg * I:51 228 do servidor X e sua │ │ │ │ │

configuração │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

xbase-clients * V:3, 132 colecção variada de │ │ │ │ │

Page 443: Referências Debian

I:47 clientes X │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

infraestrutura do │ │ │ │ │

x11-common * V:41, 568 sistema de ficheiros │ │ │ │ │

I:92 para o Sistema X │ │ │ │ │

Window │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

documentação variada │ │ │ │ │

xorg-docs * I:6 1956 para a suite de │ │ │ │ │

software X.Org │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

gera um menu Debian a│ │ │ │ │

menu * V:28, 2060 partir de todas as │ │ │ │ │

I:52 aplicações com item │ │ │ │ │

de menu │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

gksu * V:23, 540 frontend Gtk+ para o │ │ │ │ │

I:46 su(1) ou sudo(8) │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

converte a estrutura │ │ │ │ │

menu-xdg * I:47 76 do menu Debian para a│ │ │ │ │

estrutura de menu xdg│ │ │ │ │

do freedesktop.org │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

utilitários para │ │ │ │ │

Page 444: Referências Debian

V:16, integrar o ambiente │ │ │ │ │

xdg-utils * I:46 300 de trabalho │ │ │ │ │

disponibilizado pelo │ │ │ │ │

freedesktop.org │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

gnome-desktop-environment ambiente de trabalho │ │ │ │ │

* I:29 44 GNOME standard │ │ │ │ │

(meta-pacote) │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

núcleo do ambiente de│ │ │ │ │

kde-standard * I:3 36 trabalho KDE │ │ │ │ │

(metapacote) │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

Xfce ambiente de │ │ │ │ │

xfce4 * I:4 40 trabalho leve │ │ │ │ │

(meta-pacote) │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

LXDE ambiente de │ │ │ │ │

lxde-core * I:2 36 trabalho leve │ │ │ │ │

(meta-pacote) │ │ │ │ │

├─────────────────────────┼──────┼───────┼─────────────────────┤

Fluxbox: pacote para │ │ │ │ │

V:0.9, um gestor de janelas │ │ │ │ │

fluxbox * I:2 4424 X altamente │ │ │ │ │

configurável e de │ │ │ │ │

baixos recursos. │ │ │ │ │

Page 445: Referências Debian

└─────────────────────────┴──────┴───────┴─────────────────────┘

Para as bases do X, veja X(7), o manual do utilizador LDP

XWindow.

7.2. Definir o ambiente de trabalho

Um ambiente de trabalho é geralmente uma combinação de um gestor

de janelas X, um gestor de ficheiros e um conjunto de programas

utilitários compatíveis.

Você pode configurar um ambiente de trabalho completo como o

GNOME, KDE, Xfce, ou LXDE, a partir do aptitude sob o menu de

tarefas.

Dica

Task menu may be out of sync with the latest package transition

state under Debian unstable/testing environment. In such

situation, you need to deselect some (meta)packages listed under

aptitude(8) task menu to avoid package conflicts. When

deselecting (meta)packages, you must select certain packages

providing their dependencies manually to avoid them deleted

automatically.

You may alternatively setup a simple environment manually just

with a X window manager such as Fluxbox.

Page 446: Referências Debian

Veja Window Managers for X para o guia do gestor do X window e

do ambiente de trabalho.

7.2.1. Menu Debian

Debian menu system provides a general interface for both text-

and X-oriented programs with update-menus(1) from the menu

package. Each package installs its menu data in the "/usr/share/

menu/" directory. See "/usr/share/menu/README".

7.2.2. Menu Freedesktop.org

Each package which is compliant to Freedesktop.org's xdg menu

system installs its menu data provided by "*.desktop" under "/

usr/share/applications/". Modern desktop environments which are

compliant to Freedesktop.org standard use these data to generate

their menu using the xdg-utils package. See "/usr/share/doc/

xdg-utils/README".

7.2.3. Menu Debian sob o ambiente de trabalho GNOME

In order to obtain access to the traditional Debian menu under

GNOME desktop environment, you must install the menu-xdg

package, click "System" → "Preference" → "Main Menu", and check

the box for "Debian".

Dica

Page 447: Referências Debian

Você pode precisar de fazer semelhante para outros ambientes de

desktop modernos que são compatíveis com o standard

Freedesktop.org.

7.3. A relação servidor/cliente

The X Window System is activated as a combination of the server

and client programs. The meaning for the words server and client

with respect to the words local and remote requires attention

here.

Tabela 7.2. Lista de terminologia de servidor/cliente

┌──────────┬───────────────────────────────────────────────────┐

tipo descrição │ │ │

├──────────┼───────────────────────────────────────────────────┤

Servidor X um programa que corre numa máquina local ligado ao │ │ │

mostrador e dispositivos de entrada do utilizador. │ │ │

├──────────┼───────────────────────────────────────────────────┤

cliente X um programa que corre numa máquina remota que │ │ │

processa dados e fala com o servidor X. │ │ │

├──────────┼───────────────────────────────────────────────────┤

aplicação um programa que corre numa máquina remota que │ │ │

servidor processa dados e fala com os clientes. │ │ │

├──────────┼───────────────────────────────────────────────────┤

aplicação um programa que corre numa máquina local ligado ao │ │ │

Page 448: Referências Debian

cliente mostrador e dispositivos de entrada do utilizador. │ │ │

└──────────┴───────────────────────────────────────────────────┘

7.4. O servidor X

Veja xorg(1) para informação do servidor X.

7.4.1. A (re)configuração do servidor X

Nota

X server (post-lenny) is rewritten to use more information from

standardized OS services such as HAL and D-bus, for its

configuration than that from "/etc/X11/xorg.conf". So contents

in "/etc/X11/xorg.conf" are getting less. You may need to work

around transitional problems of X server.

O seguinte (re)configura um servidor X ao gerar um novo ficheiro

"/etc/X11/xorg.conf" usando o dexconf(1).

# dpkg-reconfigure --priority=low x11-common

# dpkg-reconfigure --priority=low xserver-xorg

Se editou manualmente este ficheiro "/etc/X11/xorg.conf" mas

deseja que ele seja actualizado automaticamente outra vez, corra

o seguinte comando.

Page 449: Referências Debian

# sudo dpkg-reconfigure -phigh xserver-xorg

Please check your X configuration with respect to the

specification of your monitor carefully. For the large high

resolution CRT monitor, it is a good idea to set the refresh

rate as high as your monitor can handle (85 Hz is great, 75 Hz

is OK) to reduce flicker. For the LCD monitor, slower standard

refresh rate (60Hz) is usually fine due to its slow response.

Nota

Tenha cuidado para não usar uma taxa de refrescamento muito alta

que possa causar falha fatal do hardware do seu monitor.

7.4.2. Os métodos de ligação do servidor X

Existem várias maneiras de fazer um "servidor X" (lado do

monitor) aceitar ligações de um "cliente X" (lado da aplicação).

Tabela 7.3. Lista de métodos de ligação ao servidor X

┌───────────┬──────────────┬───────┬───────┬──────────┬───────────┬──────────┐

método pacote popcon tamanho utilizador encriptação uso │ │ │ │ │ │ │ │

pertinente│ │ │ │ │ │ │ │

├───────────┼──────────────┼───────┼───────┼──────────┼───────────┼──────────┤

comando xbase-clients V:3, 132 não não obsoleto │ │ │ │ │ │ │ │

xhost * I:47 verificado │ │ │ │ │ │ │ │

Page 450: Referências Debian

├───────────┼──────────────┼───────┼───────┼──────────┼───────────┼──────────┤

comando xbase-clients V:3, ligação │ │ │ │ │ │ │ │

xauth * I:47 132 verificado não local via │ │ │ │ │ │ │ │

pipe │ │ │ │ │ │ │ │

├───────────┼──────────────┼───────┼───────┼──────────┼───────────┼──────────┤

comando ssh openssh-client V:52, ligação de│ │ │ │ │ │ │ │

-X * I:99 2104 verificado sim rede │ │ │ │ │ │ │ │

remota │ │ │ │ │ │ │ │

├───────────┼──────────────┼───────┼───────┼──────────┼───────────┼──────────┤

gestor de V:22, ligação │ │ │ │ │ │ │ │

display do gdm * I:33 16548 verificado no(XDMCP) local via │ │ │ │ │ │ │ │

GNOME pipe │ │ │ │ │ │ │ │

├───────────┼──────────────┼───────┼───────┼──────────┼───────────┼──────────┤

gestor de V:8, ligação │ │ │ │ │ │ │ │

display do kdm * I:11 5510 verificado no(XDMCP) local via │ │ │ │ │ │ │ │

KDE pipe │ │ │ │ │ │ │ │

├───────────┼──────────────┼───────┼───────┼──────────┼───────────┼──────────┤

gestor de V:0.7, ligação │ │ │ │ │ │ │ │

display do xdm * I:1.8 780 verificado no(XDMCP) local via │ │ │ │ │ │ │ │

X pipe │ │ │ │ │ │ │ │

├───────────┼──────────────┼───────┼───────┼──────────┼───────────┼──────────┤

gestor de V:24, ligação │ │ │ │ │ │ │ │

display do wdm * I:84 1992 verificado no(XDMCP) local via │ │ │ │ │ │ │ │

WindowMaker pipe │ │ │ │ │ │ │ │

├───────────┼──────────────┼───────┼───────┼──────────┼───────────┼──────────┤

Page 451: Referências Debian

ligação de│ │ │ │ │ │ │ │

gestor de V:0.02, rede SSH │ │ │ │ │ │ │ │

display do ldm * I:0.09 392 verificado sim remota │ │ │ │ │ │ │ │

LTSP (cliente │ │ │ │ │ │ │ │

ténue) │ │ │ │ │ │ │ │

└───────────┴──────────────┴───────┴───────┴──────────┴───────────┴──────────┘

Atenção

Do not use remote TCP/IP connection over unsecured network for X

connection unless you have very good reason such as use of

encryption. A remote TCP/IP socket connection without encryption

is prone to the eavesdropping attack and is disabled by default

on the Debian system. Use "ssh -X".

Atenção

Do not use XDMCP connection over unsecured network either. It

sends data via UDP/IP without encryption and is prone to the

eavesdropping attack.

Dica

You can dare to enable remote TCP/IP connection by setting

"DisallowTCP=false" in "/etc/gdm/gdm.conf" to override "/usr/

share/gdm/defaults.conf" and by removing "-nolisten" from lines

found by "find /etc/X11 -type f -print0 | xargs -0 grep

Page 452: Referências Debian

nolisten", if you are in the fully secured environment.

Dica

LTSP significa Linux Terminal Server Project.

7.5. Iniciando o X Window System

The X Window System is usually started as an X session which is

the combination of an X server and connecting X clients. For the

normal desktop system, both of them are executed on a

workstation.

A sessão X é iniciada com o seguinte.

comando startx iniciado a partir da linha de comandos●

One of the X display manager daemon programs *dm started●

from the end of the start up script in "/etc/rc?.d/" ("?"

corresponding to the runlevel) directory

Dica

The start up script for the display manager daemons checks the

content of the "/etc/X11/default-display-manager" file before

actually executing themselves. This ensures to have only one X

display manager daemon program activated.

Dica

Page 453: Referências Debian

Veja Secção 8.3.5, “O locale específico apenas sob X Window”

para as variáveis de ambiente iniciais do gestor de écran X.

Essentially, all these programs execute the "/etc/X11/Xsession"

script. Then the "/etc/X11/Xsession" script performs run-parts

(8) like action to execute scripts in the "/etc/X11/Xsession.d/"

directory. This is essentially an execution of a first program

which is found in the following order with the exec builtin

command.

1. O script especificado como o argumento de /etc/X11/Xsession"

pelo gestor de display X, se estiver definido.

2. O script "~/.xsession" ou "~/.Xsession", se estiver

definido.

3. O comando "/usr/bin/x-session-manager", se estiver definido.

4. O comando "/usr/bin/x-window-manager". se estiver definido.

5. O comando "/usr/bin/x-terminal-emulator", se estiver

definido.

This process is affected by the content of "/etc/X11/

Xsession.options". The exact programs to which these "/usr/bin/

x-*" commands point, are determined by the Debian alternative

system and changed by "update-alternatives --config

x-session-manager", etc.

7.5.1. Iniciar uma sessão X com o gdm

gdm(1) lets you select the session type (or desktop environment:

Secção 7.2, “Definir o ambiente de trabalho”), and language (or

Page 454: Referências Debian

locale: Secção 8.3, “O locale”) of the X session from its menu.

It keeps the selected default value in "~/.dmrc" as the

following.

[Desktop]

Session=default

Language=pt_PT.UTF-8

7.5.2. Personalizar a sessão X (método clássico)

On a system where "/etc/X11/Xsession.options" contains a line

"allow-user-xsession" without preceding "#" characters, any user

who defines "~/.xsession" or "~/.Xsession" is able to customize

the action of "/etc/X11/Xsession" by completely overriding the

system code. The last command in the "~/.xsession" file should

use form of "exec some-window/session-manager" to start your

favorite X window/session managers.

7.5.3. Personalizar a sessão X (método novo)

Aqui estão alguns métodos de personalizar a sessão X sem

sobrepor completamente o código do sistema como em cima.

O gestor de écran gdm pode seleccionar uma sessão específica●

e defini-la como o argumento de "/etc/X11/Xsession".

O ficheiro "~/.xsessionrc" é executado como parte do●

processo de arranque. (independente do ambiente de trabalho)

O ficheiro "~/.gnomerc" é executado como parte do processo●

de arranque. (apenas ambiente GNOME)

Page 455: Referências Debian

O software de gestão de sessão baseado em GUI pode usar o●

ficheiro "~/.gnome2/session", etc.

7.5.4. Ligar um cliente X remoto via SSH

A utilização de "ssh -X" activa uma ligação segura de um

servidor X local a um servidor de aplicações remoto.

Set "X11Forwarding" entries to "yes" in "/etc/ssh/sshd_config"

of the remote host, if you want to avoid "-X" command-line

option.

Arrancar o servidor X na máquina local.

Abrir um xterm na máquina local.

Correr o ssh(1) para estabelecer ligação com um site remoto com

o seguinte.

nome_local @ localhost $ ssh -q -X nome_de_login@domínio.máquina_remota

Palavra-passe:

Correr um comando de aplicação X, ex. "gimp", no site remoto com

o seguinte.

nome_de_login @ máquina_remota $ gimp &

Este método pode mostrar o resultado de um cliente X remoto como

se ele estivesse ligado localmente através de um socket de

Page 456: Referências Debian

domínio UNIX local.

7.5.5. Terminal X seguro via Internet

Secure X terminal via the Internet, which displays remotely run

entire X desktop environment, can easily achieved by using

specialized package such as ldm. Your local machine becomes a

secure thin client to the remote application server connected

via SSH.

Se você deseja adicionar uma funcionalidade semelhante ao seu

gestor de écran gdm normal, crie um script de shell executável

em "/usr/local/bin/ssh-session" como o seguinte.

#!/bin/sh -e

# Based on gdm-ssh-session in gdm source (GPL)

ZENITY=$(type -p zenity)

TARGETHOST=$($ZENITY --width=600 \

--title "Host to connect to" --entry \

--text "Enter the name of the host you want to log in to as [email protected]:")

TARGETSESSION=$($ZENITY --width=600 --height=400 \

--title "Remote session name" --list --radiolist --text "Select one" \

--column " " --column "Session" --column "description" --print-column 2 \

TRUE "/etc/X11/Xsession" "Debian" \

FALSE "/etc/X11/xinit/Xclients" "RH variants" \

FALSE "gnome-session" "GNOME session" \

FALSE "xterm" "Safe choice" \

FALSE "rxvt" "Safe choice" \

FALSE "gnome-terminal" "Safe choice")

Page 457: Referências Debian

echo "Connecting to "$TARGETHOST" with $TARGETSESSION"

/usr/bin/ssh -A -X -T -n "$TARGETHOST" "$TARGETSESSION"

#SSH_ASKPASS=/usr/bin/ssh-askpass /usr/bin/ssh -A -X -T -n "$TARGETHOST" "$TARGETSESSION"

Adicionar seguimentos a "/etc/dm/Sessions/ssh.desktop".

[Desktop Entry]

Encoding=UTF-8

Name=SSH

Comment=Esta sessão regista-o numa máquina remota usando ssh

Exec=/usr/local/bin/ssh-session

Type=Application

7.6. Fonts (tipos de letra) para o X Window

Fontconfig 2.0 was created to provide a distribution independent

library for configuring and customizing font access in 2002.

Debian after squeeze uses Fontconfig 2.0 for its font

configuration.

Os suportes de font no X Window System podem ser resumidos como

se segue.

Sistema de suporte a font de tamanho de servidor X Legacy●

O sistema de font do núcleo original do X11○

disponibiliza compatibilidade para trás para aplicações

cliente X de versões mais antigas.

Page 458: Referências Debian

As fonts de núcleo original X11 estão instaladas no○

servidor X.

Sistema de suporte a font de tamanho de cliente X moderno●

Modern X system supports all fonts listed below (○

Secção 7.6.1, “Fonts (tipos de letra) básicas”,

Secção 7.6.2, “Fonts (tipos de letra) adicionais”, and

Secção 7.6.3, “fonts CJK”) with advanced features such

as anti-aliasing.

Xft 2.0 connects modern X applications such as ones from○

GNOME, KDE, and OpenOffice.org with FreeType 2.0

library.

FreeType 2.0 disponibiliza uma biblioteca de○

rasterização de fonts.

Fontconfig disponibiliza resolução da especificação de○

font para Xft 2.0. Veja fonts.conf(5) para a sua

configuração.

All modern X applications using Xft 2.0 can talk to○

modern X server using the X Rendering Extension.

The X Rendering Extension moves font access and glyph○

image generation from the X server to the X client.

Tabela 7.4. Tabela de pacotes para suportar fonts do sistema X

Window

┌─────────────────┬──────┬───────┬─────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├─────────────────┼──────┼───────┼─────────────────────────────┤

Page 459: Referências Debian

xfonts-utils * V:23, 516 Programas utilitários de │ │ │ │ │

I:71 fonts do Sistema X Window │ │ │ │ │

├─────────────────┼──────┼───────┼─────────────────────────────┤

Xft, uma biblioteca que liga │ │ │ │ │

libxft2 * V:44, 148 aplicações X com a biblioteca│ │ │ │ │

I:74 de rasterização de fonts │ │ │ │ │

FreeType │ │ │ │ │

├─────────────────┼──────┼───────┼─────────────────────────────┤

libfreetype6 * V:58, 740 FreeType biblioteca de │ │ │ │ │

I:87 rasterização de fonts 2.0 │ │ │ │ │

├─────────────────┼──────┼───────┼─────────────────────────────┤

Fontconfig, uma biblioteca de│ │ │ │ │

fontconfig * V:21, 472 configuração de fonts │ │ │ │ │

I:73 genérica -- binários de │ │ │ │ │

suporte │ │ │ │ │

├─────────────────┼──────┼───────┼─────────────────────────────┤

Fontconfig, uma biblioteca de│ │ │ │ │

fontconfig-config I:81 440 configuração de fonts │ │ │ │ │

* genérica -- dados de │ │ │ │ │

configuração │ │ │ │ │

└─────────────────┴──────┴───────┴─────────────────────────────┘

Você pode verificar informação de configuração de fonts pelo

seguinte.

Page 460: Referências Debian

"xset q" para caminho das fonts do núcleo do X11●

"fc-match" para a font predefinida do fontconfig●

"fc-list" para fonts disponíveis do fontconfig●

Dica

"The Penguin and Unicode" is a good overview of modern X Window

System. Other documentations at http://unifont.org/ should

provide good information on Unicode fonts, Unicode-enabled

software, internationalization, and Unicode usability issues on

free/libre/open source (FLOSS) operating systems.

7.6.1. Fonts (tipos de letra) básicas

Existem 2 tipos principais de fonts de computador.

Fonts bitmap (boas para rasterização de baixa resolução)●

Fonts outline/stroke (boas para rasterização de alta●

resolução)

While scaling of bitmap fonts causes jugged image, scaling of

outline/stroke fonts produces smooth image.

Bitmap fonts on the Debian system are usually provided by

compressed X11 pcf bitmap font files having their file extension

".pcf.gz".

As fonts de contorno no sistema Debian são disponibilizadas pelo

seguinte.

Page 461: Referências Debian

Ficheiros de font Type 1 PostScript tendo a sua extensão de●

ficheiro ".pfb" (ficheiro de font binário) e ".afm"

(ficheiro de font métrica).

Ficheiros font TrueType (ou OpenType) geralmente tendo a sua●

extensão de ficheiro ".ttf".

Dica

OpenType é destinado a substituir ambas TrueType e PostScript

Type 1.

Tabela 7.5. Tabela de fonts PostScript Type 1 correspondentes

┌───────────┬──────┬───────┬──────────┬────────┬─────────────┬──────────┐

pacote font popcon tamanho font font font fonte da │ │ │ │ │ │ │ │

sans-serif serif monospace font │ │ │ │ │ │ │ │

├───────────┼──────┼───────┼──────────┼────────┼─────────────┼──────────┤

PostScript N/D N/D Helvetica Times Courier Adobe │ │ │ │ │ │ │ │

├───────────┼──────┼───────┼──────────┼────────┼─────────────┼──────────┤

Nimbus URW │ │ │ │ │ │ │ │

gsfonts * V:18, 4632 Nimbus Roman Nimbus Mono L (tamanho │ │ │ │ │ │ │ │

I:66 Sans L No9 L compatível│ │ │ │ │ │ │ │

com Adobe)│ │ │ │ │ │ │ │

├───────────┼──────┼───────┼──────────┼────────┼─────────────┼──────────┤

Suporte a │ │ │ │ │ │ │ │

gsfonts-x11 Nimbus Nimbus X font com│ │ │ │ │ │ │ │

Page 462: Referências Debian

* I:30 116 Sans L Roman Nimbus Mono L fonts │ │ │ │ │ │ │ │

No9 L PostScript│ │ │ │ │ │ │ │

Type 1. │ │ │ │ │ │ │ │

├───────────┼──────┼───────┼──────────┼────────┼─────────────┼──────────┤

URW │ │ │ │ │ │ │ │

t1-cyrillic Free Free extenso │ │ │ │ │ │ │ │

* I:1.9 5008 Helvetian Times Free Courier (tamanho │ │ │ │ │ │ │ │

compatível│ │ │ │ │ │ │ │

com Adobe)│ │ │ │ │ │ │ │

├───────────┼──────┼───────┼──────────┼────────┼─────────────┼──────────┤

fonts │ │ │ │ │ │ │ │

PostScript│ │ │ │ │ │ │ │

e OpenType│ │ │ │ │ │ │ │

V:2, escaláveis│ │ │ │ │ │ │ │

lmodern * I:16 45644 LMSans* LMRoman* LMTypewriter* baseadas │ │ │ │ │ │ ││

em │ │ │ │ │ │ │ │

Computer │ │ │ │ │ │ │ │

Modern (do│ │ │ │ │ │ │ │

TeX) │ │ │ │ │ │ │ │

└───────────┴──────┴───────┴──────────┴────────┴─────────────┴──────────┘

Tabela 7.6. Tabela de fonts correspondentes a TrueType

┌─────────────────────────┬──────┬───────┬──────────┬──────────┬──────────┬────────────────┐

Page 463: Referências Debian

pacote font popcon tamanho font font serif font fonte da font│ │ │ │ │ │ │ │

sans-serif monospace │ │ │ │ │ │ │ │

├─────────────────────────┼──────┼───────┼──────────┼──────────┼──────────┼────────────────┤

Microsoft │ │ │ │ │ │ │ │

(tamanho │ │ │ │ │ │ │ │

ttf-mscorefonts-installer I:11 200 Arial Times New Courier │ │ │ │ │ │compatível com │ │

* Roman New Adobe) (Isto │ │ │ │ │ │ │ │

instala dados │ │ │ │ │ │ │ │

não-livres) │ │ │ │ │ │ │ │

├─────────────────────────┼──────┼───────┼──────────┼──────────┼──────────┼────────────────┤

Liberation Fonts│ │ │ │ │ │ │ │

ttf-liberation * I:43 1724 Liberation Liberation Liberation project │ │ │ │ │ │ │(tamanho│

Sans Serif Mono compatível com │ │ │ │ │ │ │ │

Microsoft) │ │ │ │ │ │ │ │

├─────────────────────────┼──────┼───────┼──────────┼──────────┼──────────┼────────────────┤

GNU freefont │ │ │ │ │ │ │ │

ttf-freefont * V:10, 4204 FreeSans FreeSerif FreeMono │ │ │ │ │ │((tamanho │ │

I:26 compatível com │ │ │ │ │ │ │ │

Microsoft) │ │ │ │ │ │ │ │

├─────────────────────────┼──────┼───────┼──────────┼──────────┼──────────┼────────────────┤

DejaVu, │ │ │ │ │ │ │ │

ttf-dejavu * I:77 68 DejaVu DejaVu DejaVu Bitstream Vera│ │ │ │ │ │ │ │

Sans Serif Sans Mono com cobertura │ │ │ │ │ │ │ │

Unicode │ │ │ │ │ │ │ │

Page 464: Referências Debian

├─────────────────────────┼──────┼───────┼──────────┼──────────┼──────────┼────────────────┤

DejaVu, │ │ │ │ │ │ │ │

Bitstream Vera │ │ │ │ │ │ │ │

com cobertura │ │ │ │ │ │ │ │

DejaVu DejaVu DejaVu Unicode (sans, │ │ │ │ │ │ │ │

ttf-dejavu-core * I:72 2592 Sans Serif Sans Mono sans-│ │ │ │ │ │ │negrito, │

serif. │ │ │ │ │ │ │ │

serif-negrito, │ │ │ │ │ │ │ │

mono, │ │ │ │ │ │ │ │

mono-negrito) │ │ │ │ │ │ │ │

├─────────────────────────┼──────┼───────┼──────────┼──────────┼──────────┼────────────────┤

DejaVu, │ │ │ │ │ │ │ │

Bitstream Vera │ │ │ │ │ │ │ │

com cobertura │ │ │ │ │ │ │ │

Unicode │ │ │ │ │ │ │ │

ttf-dejavu-extra * I:69 5788 N/D N/D N/D (oblíquo, │ │ │ │ │ │ │ │

itálico, │ │ │ │ │ │ │ │

negrito-oblíquo,│ │ │ │ │ │ │ │

negrito-itálico,│ │ │ │ │ │ │ │

condensado) │ │ │ │ │ │ │ │

├─────────────────────────┼──────┼───────┼──────────┼──────────┼──────────┼────────────────┤

GNU Unifont, com│ │ │ │ │ │ │ │

todo o código de│ │ │ │ │ │ │ │

caracteres │ │ │ │ │ │ │ │

ttf-unifont * I:4 16060 N/D N/D unifont imprimíveis em │ │ │ │ │ │ │ │

Unicode 5.1 │ │ │ │ │ │ │ │

Page 465: Referências Debian

Basic │ │ │ │ │ │ │ │

Multilingual │ │ │ │ │ │ │ │

Plane (BMP) │ │ │ │ │ │ │ │

└─────────────────────────┴──────┴───────┴──────────┴──────────┴──────────┴────────────────┘

Dica

as fonts DejaVu são baseadas e um super conjunto da fonts

Bitstream Vera.

7.6.2. Fonts (tipos de letra) adicionais

O aptitude(8) ajuda-o a encontrar fonts adicionais facilmente.

A lista de pacotes curta sob "Tarefas" → "Localização"●

A lista de pacotes lisa filtrada de dados de fonts com regex●

em debtag: "~Gmade-of::data:font"

A lista de pacotes lisa filtrada de pacotes de fonts BDF●

(bitmap) com regex no nome do pacote: "~nxfonts-"

A lista de pacotes lisa filtrada de pacotes de fonts●

TrueType (contorno) com regex no nome do pacote: "~nttf-"

Since Free fonts are sometimes limited, installing or sharing

some commercial TrueType fonts is an option for a Debian users.

In order to make this process easy for the user, some

convenience packages have been created.

Page 466: Referências Debian

ttf-mathematica4.1●

ttf-mscorefonts-installer●

You'll have a really good selection of TrueType fonts at the

expense of contaminating your Free system with non-Free fonts.

7.6.3. fonts CJK

Aqui estão alguns pontos chave que focam em fonts de caracteres

CJK.

Tabela 7.7. Tabela de palavras chave usadas em nomes de fonts

CJK para indicar os tipos de fonts.

┌──────────┬─────────────────┬────────────────┬────────────────┐

tipo de nome de font nome de font nome de font │ │ │ │ │

font Japonesa Chinesa Coreana │ │ │ │ │

├──────────┼─────────────────┼────────────────┼────────────────┤

sans-serif gótico, │ │ ゴチック │hei, gótico dodum, gulim, │ │

gótico │ │ │ │ │

├──────────┼─────────────────┼────────────────┼────────────────┤

serif mincho, │ │ 明朝 │song, ming batang │ │

└──────────┴─────────────────┴────────────────┴────────────────┘

Font name such as "VL PGothic" with "P" is a proportional font

Page 467: Referências Debian

which corresponds to the fixed width "VL Gothic" font.

For example, Shift_JIS code table comprises 7070 characters.

They can be grouped as the following.

JIS X 0201 single-byte characters (191 characters, a.k.a.●

half-width characters)

JIS X 0208 double-byte characters (6879 characters, a.k.a.●

full-width characters)

Double-byte characters occupy double width on console terminals

which uses CJK fixed width fonts. In order to cope with such

situation, Hanzi Bitmap Font (HBF) File with file extension

".hbf" may be deployed for fonts containing single-byte and

double-byte characters.

In order to save space for TrueType font files, TrueType font

collection file with file extension ".ttc" may be used.

In order to cover complicated code space of characters, CID

keyed PostScript Type 1 font is used with CMap files starting

themselves with "%!PS-Adobe-3.0 Resource-CMap". This is rarely

used for normal X display but used for PDF rendering etc. (see

Secção 7.7.2, “aplicações utilitárias do X”).

Dica

The multiple glyphs are expected for some Unicode code points

due to Han unification. One of the most annoying ones are

Page 468: Referências Debian

"U+3001 IDEOGRAPHIC COMMA" and "U+3002 IDEOGRAPHIC FULL STOP"

whose character positions differ among CJK countries.

Configuring priority of Japanese centric fonts over Chinese ones

using "~/.fonts.conf" should give peace of minds to Japanese.

7.7. Aplicações do X

7.7.1. Aplicações de escritório do X

Aqui está uma lista de aplicações de escritório básicas (OO é o

OpenOffice.org).

Tabela 7.8. lista de aplicações X de escritório básicas

┌──────────────────────┬───────┬───────┬─────┬─────────────────┐

tamanho │ │ │ │ │ │

pacote popcon do tipo descrição │ │ │ │ │ │

pacote │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

openoffice.org-writer V:21, 26892 OO processador de │ │ │ │ │ │

* I:41 texto │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

openoffice.org-calc * V:21, 20524 OO folha de cálculo │ │ │ │ │ │

I:40 │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

openoffice.org-impress V:18, 4208 OO apresentação │ │ │ │ │ │

* I:40 │ │ │ │ │ │

Page 469: Referências Debian

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

openoffice.org-base * V:16, 10708 OO gestão de base de│ │ │ │ │ │

I:39 dados │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

editor de │ │ │ │ │ │

openoffice.org-draw * V:18, 10720 OO gráficos │ │ │ │ │ │

I:40 vectoriais │ │ │ │ │ │

(desenho) │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

V:17, editor de │ │ │ │ │ │

openoffice.org-math * I:40 2712 OO fórmulas/equações│ │ │ │ │ │

matemáticas │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

abiword * V:6, 4776 GNOME processador de │ │ │ │ │ │

I:10 texto │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

gnumeric * V:5, 7860 GNOME folha de cálculo │ │ │ │ │ │

I:11 │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

V:12, editor de │ │ │ │ │ │

gimp * I:44 13560 GTK gráficos bitmap │ │ │ │ │ │

(pintura) │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

editor de │ │ │ │ │ │

inkscape * V:15, 87436 GNOME gráficos │ │ │ │ │ │

Page 470: Referências Debian

I:32 vectoriais │ │ │ │ │ │

(desenho) │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

V:1.4, editor de │ │ │ │ │ │

dia-gnome * I:2 576 GNOME fluxogramas e │ │ │ │ │ │

diagramas │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

planner * V:0.4, 6704 GNOME gestão de │ │ │ │ │ │

I:4 projectos │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

kword * V:0.6, 5334 KDE processador de │ │ │ │ │ │

I:1.5 texto │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

kspread * V:0.6, 8792 KDE folha de cálculo │ │ │ │ │ │

I:1.6 │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

kpresenter * V:0.5, 2877 KDE apresentação │ │ │ │ │ │

I:1.3 │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

kexi * V:0.2, 7625 KDE gestão de base de│ │ │ │ │ │

I:1.6 dados │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

editor de │ │ │ │ │ │

karbon * V:0.6, 2403 KDE gráficos │ │ │ │ │ │

I:1.4 vectoriais │ │ │ │ │ │

Page 471: Referências Debian

(desenho) │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

V:0.6, editor de │ │ │ │ │ │

krita * I:1.6 11822 KDE gráficos bitmap │ │ │ │ │ │

(pintura) │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

V:0.8, program de │ │ │ │ │ │

kchart * I:1.9 2503 KDE desenho de grafos│ │ │ │ │ │

e gráficos │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

V:0.4, editor de │ │ │ │ │ │

kformula * I:1.3 2065 KDE fórmulas/equações│ │ │ │ │ │

matemáticas │ │ │ │ │ │

├──────────────────────┼───────┼───────┼─────┼─────────────────┤

kplato * V:0.15, 5978 KDE gestão de │ │ │ │ │ │

I:1.4 projectos │ │ │ │ │ │

└──────────────────────┴───────┴───────┴─────┴─────────────────┘

7.7.2. aplicações utilitárias do X

Aqui está uma lista de aplicações utilitárias básicas que me

chamaram a atenção.

Tabela 7.9. Lista de aplicações X utilitárias básicas

Page 472: Referências Debian

┌─────────┬───────┬─────────┬─────┬────────────────────────────┐

pacote popcon tamanho tipo descrição │ │ │ │ │ │

do pacote │ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

evince * V:26, 1116 GNOME visualizador de documentos │ │ │ │ │ │

I:38 (pdf) │ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

okular * V:4, 3408 KDE visualizador de documentos │ │ │ │ │ │

I:6 (pdf) │ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

evolution V:16, 4724 GNOME Gestor de Informações │ │ │ │ │ │

* I:34 Pessoais (groupware e email)│ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

kontact * V:1.3, 1326 KDE Gestor de Informações │ │ │ │ │ │

I:8 Pessoais (groupware e email)│ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

V:0.5, editor de disposição de │ │ │ │ │ │

scribus * I:3 26888 KDE páginas do ambiente de │ │ │ │ │ │

trabalho │ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

glabels * V:0.16, 1148 GNOME editor de etiquetas │ │ │ │ │ │

I:0.7 │ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

kbarcode V:0.05, aplicação de códigos de │ │ │ │ │ │

Page 473: Referências Debian

* I:0.3 2180 KDE barras e impressão de │ │ │ │ │ │

etiquetas │ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

gnucash * V:0.7, 5748 GNOME contas pessoais │ │ │ │ │ │

I:2 │ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

homebank V:0.09, 1092 GTK contas pessoais │ │ │ │ │ │

* I:0.4 │ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

kmymoney2 V:0.06, 144 KDE contas pessoais │ │ │ │ │ │

* I:0.5 │ │ │ │ │ │

├─────────┼───────┼─────────┼─────┼────────────────────────────┤

xsane * V:5, 748 GTK frontend para digitalizador │ │ │ │ │ │

I:36 (scanner) │ │ │ │ │ │

└─────────┴───────┴─────────┴─────┴────────────────────────────┘

Cuidado

The poppler-data package (previously non-free, see

Secção 11.3.1, “Ghostscript”) needs to be installed for evince

and okular to display CJK PDF documents using Cmap data (

Secção 7.6.3, “fonts CJK”).

Nota

Page 474: Referências Debian

Installing softwares such as scribus (KDE) on GNOME desktop

environment are quite acceptable since corresponding

functionality is not available under GNOME desktop environment.

But installing too many packages with duplicated functionalities

clutter your menu.

7.8. The X trivia

7.8.1. Mapas de teclas e mapas de botões do apontador (rato) no

X

xmodmap(1) is a utility for modifying keymaps and pointer button

mappings in the X Window System. To get the keycode, run xev(1)

in the X and press keys. To get the meaning of keysym, look into

the MACRO definition in "/usr/include/X11/keysymdef.h" file

(x11proto-core-dev package). All "#define" statements in this

file are named as "XK_" prepended to keysym names.

7.8.2. Clientes X Clássicos

Most traditional X client programs, such as xterm(1), can be

started with a set of standard command line options to specify

geometry, font, and display.

They also use the X resource database to configure their

appearance. The system-wide defaults of X resources are stored

in "/etc/X11/Xresources/*" and application defaults of them are

stored in "/etc/X11/app-defaults/*". Use these settings as the

starting points.

Page 475: Referências Debian

The "~/.Xresources" file is used to store user resource

specifications. This file is automatically merged into the

default X resources upon login. To make changes to these

settings and make them effective immediately, merge them into

the database using the following command.

$ xrdb -merge ~/.Xresources

Veja x(7) e xrdb(1).

7.8.3. O emulador de terminal X - xterm

Saiba tudo sobre o xterm(1) em http://dickey.his.com/xterm/

xterm.faq.html.

7.8.4. Correr clientes X como root

Atenção

Never start the X display/session manager under the root account

by typing in root to the prompt of the display manager such as

gdm because it is considered unsafe (insecure), even when you

plan to perform administrative activities. The entire X

architecture is considered insecure if run as root. You must

always use the lowest privilege level possible, like a regular

user account.

Maneiras fáceis de correr um cliente X particular, ex. "foo"

Page 476: Referências Debian

como root é usar sudo(8) etc. como o seguinte.

$ sudo foo &

$ sudo -s

# foo &

$ gksu foo &

$ ssh -X root@localhost

# foo &

Cuidado

O uso de ssh(1) só para este objectivo como em cima é um

desperdício de recursos.

De modo que o cliente X se ligue ao servidor X, por favor note o

seguinte.

Values of the old user's "$XAUTHORITY" and "$DISPLAY"●

environment variables must be copied to the new user's ones.

O ficheiro apontado pelo valor da variável de ambiente●

"$XAUTHORITY" tem de ser legível pelo novo utilizador.

The gksu package (popcon: V:23, I:46) is a specialized GTK+ GUI

package for gaining the root privileges. It can be configured to

use su(1) or sudo(8) as its backend depending on the "/apps/gksu

/sudo-mode" gconf key. You can edit gconf key using gconf-editor

Page 477: Referências Debian

(1) (menu: "Applications" → "System Tools" → "Configuration

Editor").

Capítulo 8. I18N e L10N

Multilingualization (M17N) or Native Language Support for an

application software is done in 2 steps.

Internationalization (I18N): To make a software potentially●

handle multiple locales.

Localization (L10N): Tornar o software útil num locale●

específico.

Dica

There are 17, 18, or 10 letters between "m" and "n", "i" and

"n", or "l" and "n" in multilingualization,

internationalization, and localization which correspond to M17N,

I18N, and L10N.

The modern software such as GNOME and KDE are multilingualized.

They are internationalized by making them handle UTF-8 data and

localized by providing their translated messages through the

gettext(1) infrastructure. Translated messages may be provided

as separate localization packages. They can be selected simply

by setting pertinent environment variables to the appropriate

locale.

The simplest representation of the text data is ASCII which is

Page 478: Referências Debian

sufficient for English and uses less than 127 characters

(representable with 7 bits). In order to support much more

characters for the international support, many character

encoding systems have been invented. The modern and sensible

encoding system is UTF-8 which can handle practically all the

characters known to the human (see Secção 8.3.1, “Bases de

codificação”).

Veja Introdução ao i18n para mais detalhes.

O suporte a hardware internacional é activado com dados de

configuração de hardware localizados.

8.1. A entrada do teclado

O sistema Debian pode ser configurado para funcionar com muitas

disposições internacionais de teclado.

Tabela 8.1. Lista de métodos de configuração do teclado

┌────────────────┬────────────────────────────────────────────┐

ambiente comando │ │ │

├────────────────┼────────────────────────────────────────────┤

Consola do Linux dpkg-reconfigure --priority=low console-data│ │ │

├────────────────┼────────────────────────────────────────────┤

X Window dpkg-reconfigure --priority=low xserver-xorg│ │ │

└────────────────┴────────────────────────────────────────────┘

Page 479: Referências Debian

This supports keyboard input for accented characters of many

European languages with its dead-key function. For Asian

languages, you need more complicated input method support such

as IBus discussed next.

8.1.1. O suporte a método de entrada com IBus

Setup of multilingual input for the Debian system is simplified

by using the IBus family of packages with the im-config package.

The list of IBus packages are the following.

Tabela 8.2. Lista de suportes a método de entrada com IBus

┌───────────────┬─────────┬───────┬────────────────────────────┐

pacote popcon tamanho locale suportado │ │ │ │ │

├───────────────┼─────────┼───────┼────────────────────────────┤

ibus * V:0.2, 4220 estrutura de método de │ │ │ │ │

I:0.2 entrada que usa dbus │ │ │ │ │

├───────────────┼─────────┼───────┼────────────────────────────┤

ibus-anthy * V:0.04, 684 Japonês │ │ │ │ │

I:0.10 │ │ │ │ │

├───────────────┼─────────┼───────┼────────────────────────────┤

ibus-skk * V:0.00, 404 , , │ │ │ │ │

I:0.03 │ │ │ │ │

Page 480: Referências Debian

├───────────────┼─────────┼───────┼────────────────────────────┤

ibus-pinyin * V:0.06, 1184 Chinês (para zh_CN) │ │ │ │ │

I:0.09 │ │ │ │ │

├───────────────┼─────────┼───────┼────────────────────────────┤

ibus-chewing * V:0.01, 252 , , (para zh_TW) │ │ │ │ │

I:0.02 │ │ │ │ │

├───────────────┼─────────┼───────┼────────────────────────────┤

ibus-hangul * V:0.01, 216 Coreano │ │ │ │ │

I:0.03 │ │ │ │ │

├───────────────┼─────────┼───────┼────────────────────────────┤

ibus-table * V:0.05, 680 motor de tabela para IBus │ │ │ │ │

I:0.10 │ │ │ │ │

├───────────────┼─────────┼───────┼────────────────────────────┤

ibus-table-thai I:0.00 156 160 Thai │ │ │ │ │

* │ │ │ │ │

├───────────────┼─────────┼───────┼────────────────────────────┤

ibus-unikey * V:0.00, 316 Vietnamita │ │ │ │ │

I:0.00 │ │ │ │ │

├───────────────┼─────────┼───────┼────────────────────────────┤

ibus-m17n * V:0.02, 180 Multilingue: Indiano, Árabe │ │ │ │ │

I:0.05 e outros │ │ │ │ │

└───────────────┴─────────┴───────┴────────────────────────────┘

Page 481: Referências Debian

The kinput2 method and other locale dependent Asian classic

input methods still exist but are not recommended for the modern

UTF-8 X environment. The SCIM and uim tool chains are an

slightly older approach for the international input method for

the modern UTF-8 X environment.

8.1.2. Um exemplo para Japonês

I find the Japanese input method started under English

environment ("en_US.UTF-8") very useful. Here is how I did this

with IBus.

1. Install the Japanese input tool package ibus-anthy with its

recommended packages such as im-config.

2. Execute "im-config" a partir da shell de utilizador e

seleccione "ibus".

3. Select "System" → "Preferences" → "IBus Preferences" →

"Input Method" → "Select an input method" → "Japanese" →

"Anthy" and click "Add".

4. Relogin to user's account.

5. Verificar definição por "im-config".

6. Setup input method and mode by right clicking GUI toolbar.

(You can reduce menu choice of input method.)

7. Arrancar o método de entrada IBus por CTRL-ESPAÇO.

Por favor note o seguinte.

im-config(8) behaves differently if command is executed from●

root or not.

Page 482: Referências Debian

im-config(8) activa o melhor método de entrada do sistema e●

é predefinido sem qualquer acção do utilizador.

The GUI menu entry for im-config(8) is disable as default to●

prevent cluttering.

8.1.3. Desactivar o método de entrada

If you wish to input without going through XIM, set

"$XMODIFIERS" value to "none" while starting a program. This may

be the case if you use Japanese input infrastructure egg on

emacs(1). From shell, execute as the following.

$ XMODIFIERS=none emacs

In order to adjust the command executed by the Debian menu,

place customized configuration in "/etc/menu/" following method

described in "/usr/share/doc/menu/html".

8.2. O mostrador de resultados

A consola do Linux apenas pode mostrar caracteres limitados.

(Você precisa usar programas de terminal especiais como o

jfbterm(1) para mostrar linguagens não-Europeias numa consola

não-X.)

X Window can display any characters in the UTF-8 as long as

required font data exists. (The encoding of the original font

data is taken care by the X Window System and transparent to the

user.)

Page 483: Referências Debian

8.3. O locale

O seguinte foca-se no locale para aplicações que correm sob

ambiente X Window iniciado a partir do gdm(1).

8.3.1. Bases de codificação

A variável de ambiente "LANG=xx_YY.ZZZZ" define o locale para o

código de linguagem "xx", código de país "yy", e codificação

"ZZZZ" (veja Secção 1.5.2, “variável "$LANG"”).

Current Debian system normally sets the locale as "LANG=

xx_YY.UTF-8". This uses the UTF-8 encoding with the Unicode

character set. This UTF-8 encoding system is a multibyte code

system and uses code points smartly. The ASCII data, which

consist only with 7-bit range codes, are always valid UTF-8 data

consisting only with 1 byte per character.

Previous Debian system used to set the locale as "LANG=C" or

"LANG=xx_YY" (without ".UTF-8").

The ASCII character set is used for "LANG=C" or "LANG=●

POSIX".

The traditional encoding system in Unix is used for "LANG=●

xx_YY".

Actual traditional encoding system used for "LANG=xx_YY" can be

identified by checking "/usr/share/i18n/SUPPORTED". For example,

Page 484: Referências Debian

"en_US" uses "ISO-8859-1" encoding and "fr_FR@euro" uses

"ISO-8859-15" encoding.

Dica

For meaning of encoding values, see Tabela 11.2, “Lista de

valores de codificação e a sua utilização”.

8.3.2. Rationale for UTF-8 locale

The UTF-8 encoding is the modern and sensible text encoding

system for I18N and enables to represent Unicode characters,

i.e., practically all characters known to human. UTF stands for

Unicode Transformation Format (UTF) schemes.

I recommend to use UTF-8 locale for your desktop, e.g., "LANG=

en_US.UTF-8". The first part of the locale determines messages

presented by applications. For example, gedit(1) (text editor

for the GNOME Desktop) under "LANG=fr_FR.UTF-8" locale can

display and edit Chinese character text data while presenting

menus in French, as long as required fonts and input methods are

installed.

I also recommend to set the locale only using the "$LANG"

environment variable. I do not see much benefit of setting a

complicated combination of "LC_*" variables (see locale(1))

under UTF-8 locale.

Even plain English text may contain non-ASCII characters, e.g.

Page 485: Referências Debian

left and right quotation marks are not available in ASCII.

“double quoted text”

‘single quoted text’

When ASCII plain text data is converted to UTF-8 one, it has

exactly the same content and size as the original ASCII one. So

you loose nothing by deploying UTF-8 locale.

Some programs consume more memory after supporting I18N. This is

because they are coded to use UTF-32(UCS4) internally to support

Unicode for speed optimization and consume 4 bytes per each

ASCII character data independent of locale selected. Again, you

loose nothing by deploying UTF-8 locale.

The vendor specific old non-UTF-8 encoding systems tend to have

minor but annoying differences on some characters such as

graphic ones for many countries. The deployment of the UTF-8

system by the modern OSs practically solved these conflicting

encoding issues.

8.3.3. A reconfiguração do locale

In order for the system to access a particular locale, the

locale data must be compiled from the locale database. (The

Debian system does not come with all available locales

pre-compiled unless you installed the locales-all package.) The

full list of supported locales available for compiling are

listed in "/usr/share/i18n/SUPPORTED". This lists all the proper

Page 486: Referências Debian

locale names. The following lists all the available UTF-8

locales already compiled to the binary form.

$ locale -a | grep utf8

A execução do comando seguinte reconfigura o pacote locales.

# dpkg-reconfigure locales

Este processo involve 3 passos.

1. Actualizar a lista de locales disponíveis

2. Compilá-los num formato binário

3. Definir o locale predefinido de todo o sistema em "/etc/

defaults/locale" para usar com o PAM (veja Secção 4.5, “PAM

e NSS”)

A lista dos locale disponíveis deve incluir "en_US.UTF-8" e

todas as linguagens de interesse com "UTF-8".

O locale predefinido recomendado é "en_US.UTF-8" para Inglês dos

Estados Unidos. Para outras linguagens, por favor certifique-se

de escolher um locale com "UTF-8". Qualquer uma destas

definições consegue lidar com quaisquer caracteres

internacionais.

Nota

Apesar da definição de locale para "C" usar mensagens em Inglês

Page 487: Referências Debian

dos Estados Unidos, apenas lida com caracteres ASCII.

8.3.4. O valor da variável de ambiente "$LANG"

O valor da variável de ambiente "$LANG" é definido e alterado

por muitas aplicações.

Definido inicialmente pelo mecanismo de login(1) PAM para os●

programas de consola local do Linux

Definido inicialmente pelo mecanismo PAM do gestor de ecrã●

para todos os programas do X

Definido inicialmente pelo mecanismo PAM do ssh(1) para os●

programas de consola remota.

Alterado por algum gestor de ecrã como o gdm(1) para todos●

os programas do X

Alterado pelo código de arranque da sessão X via "~●

/.xsessionrc" para todos os programas do X (funcionalidade

do lenny)

Alterado pelo código de arranque da shell, ex. "~/.bashrc",●

para todos os programas de consola

Dica

É uma boa ideia instalar um locale predefinido para todo o

sistema como "en_US.UTF-8" para o máximo de compatibilidade.

8.3.5. O locale específico apenas sob X Window

Você pode escolher um locale específico apenas sob X Window não

Page 488: Referências Debian

relacionado com o seu locale predefinido de todo o sistema

usando personalização do PAM (veja xref linkend="_pam_and_nss"

/>) como se segue.

Este ambiente deverá disponibilizar-lhe a melhor experiência de

ambiente de trabalho com estabilidade. Você tem acesso ao

terminal de caracteres funcional com mensagens legíveis mesmo

quando o Sistema X Window não está a funcionar. Isto torna-se

essencial para linguagens que usam caracteres não-romanos como o

Chinês, Japonês e Coreano.

Nota

There may be another way available as the improvement of X

session manager package but please read following as the generic

and basic method of setting the locale. For gdm(1), I know you

can select the locale of X session via its memu.

A seguinte linha define a localização do ficheiro do ambiente de

linguagem no ficheiro do configuração do PAM, como o "/etc/pam.d

/gdm.

auth required pam_env.so read_env=1 envfile=/etc/default/locale

Mude isto para o seguinte.

auth required pam_env.so read_env=1 envfile=/etc/default/locale-x

Para Japonês, crie um ficheiro "/etc/defaults/locale-gdm" com

Page 489: Referências Debian

permissões "-rw-r--r-- 1 root root" contendo o seguinte.

LANG="ja_JP.UTF-8"

Mantenha o ficheiro "/etc/defaults/locale" predefinido para

outros programas com o seguinte.

LANG="en_US.UTF-8"

Esta é a técnica mais genérica para personalizar o locale e faz

com que o diálogo de selecção de menu do próprio gdm(1) fique

localizado (traduzido).

Alternativamente para este caso, você pode simplesmente alterar

o locale usando o ficheiro "~/.xsessionrc".

8.3.6. Codificação de nomes de ficheiros

For cross platform data exchanges (see Secção 10.1.10,

“Dispositivo de armazenamento amovível”), you may need to mount

some filesystem with particular encodings. For example, mount(8)

for vfat filesystem assumes CP437 if used without option. You

need to provide explicit mount option to use UTF-8 or CP932 for

filenames.

Nota

When auto-mounting a hot-pluggable USB memory stick under modern

desktop environment such as GNOME, you may provide such mount

Page 490: Referências Debian

option by right clicking the icon on the desktop, click "Drive"

tab, click to expand "Setting", and entering "utf8" to "Mount

options:". The next time this memory stick is mounted, mount

with UTF-8 is enabled.

Nota

If you are upgrading system or moving disk drives from older

non-UTF-8 system, file names with non-ASCII characters may be

encoded in the historic and deprecated encodings such as

ISO-8859-1 or eucJP. Please seek help of text conversion tools

to convert them to UTF-8. See Secção 11.1, “Ferramentas de

conversão de dados em texto”.

Samba uses Unicode for newer clients (Windows NT, 200x, XP) but

uses CP850 for older clients (DOS and Windows 9x/Me) as default.

This default for older clients can be changed using "dos

charset" in the "/etc/samba/smb.conf" file, e.g., to CP932 for

Japanese.

8.3.7. Mensagens localizadas e documentação traduzida

Translations exist for many of the text messages and documents

that are displayed in the Debian system, such as error messages,

standard program output, menus, and manual pages. GNU gettext(1)

command tool chain is used as the backend tool for most

translation activities.

aptitude(8) lists under "Tasks" → "Localization" provide

Page 491: Referências Debian

extensive list of useful binary packages which add localized

messages to applications and provide translated documentation.

For example, you can obtain the localized message for manpage by

installing the manpages-<LANG> package. To read the

Italian-language manpage for <programname> from "/usr/share/man/

it/", execute as the following.

LANG=it_IT.UTF-8 man <nome_do_programa>

8.3.8. Efeitos do locale

The sort order of characters with sort(1) is affected by the

language choice of the locale. Spanish and English locale sort

differently.

The date format of ls(1) is affected by the locale. The date

format of "LANG=C ls -l" and "LANG=en_US.UTF-8" are different

(see Secção 9.2.5, “Amostragem personalizada de hora e data”).

Number punctuation are different for locales. For example, in

English locale, one thousand one point one is displayed as

"1,000.1" while in German locale, it is displayed as "1.000,1".

You may see this difference in spreadsheet program.

Capítulo 9. Dicas do sistema

Aqui, eu descrevo dicas básicas para configurar e gerir

sistemas, a maioria a partir da consola.

Page 492: Referências Debian

9.1. O programa screen

O screen(1) é uma ferramenta muito útil para se aceder a sites

remotos via ligações não confiáveis e intermitentes porque

suporta interrupções nas ligações de rede.

Tabela 9.1. Lista de programas para suportar ligações à rede

interrompidas

┌──────┬───────┬───────┬───────────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├──────┼───────┼───────┼───────────────────────────────────────┤

screen V:11, 952 terminal multiplexador com emulação de │ │ │ │ │

* I:34 terminal VT100/ANSI │ │ │ │ │

└──────┴───────┴───────┴───────────────────────────────────────┘

9.1.1. O cenário de utilização para o screen(1)

screen(1) not only allows one terminal window to work with

multiple processes, but also allows remote shell process to

survive interrupted connections. Here is a typical use scenario

of screen(1).

1. Você faz login numa máquina remota.

2. Você arranca o screen numa consola única.

Page 493: Referências Debian

3. Você executa múltiplos programas na janela criada do screen

com ^A c ("Ctrl-A" seguido de "c").

4. Você muda entre as múltiplas janelas do screen com ^A n

("Ctrl-A" seguido de "n").

5. Suddenly you need to leave your terminal, but you don't want

to lose your active work by keeping the connection.

6. You may detach the screen session by any methods.

Desligar a sua ligação de rede à bruta●

Type ^A d ("Control-A" followed by "d") and manually●

logging out from the remote connection

Type ^A DD ("Control-A" followed by "DD") to have screen●

detach and log you out

7. You log in again to the same remote machine (even from a

different terminal).

8. Você inicia o screen como "screen -r".

9. screen magically reattaches all previous screen windows with

all actively running programs.

Dica

You can save connection fees with screen for metered network

connections such as dial-up and packet ones, because you can

leave a process active while disconnected, and then re-attach it

later when you connect again.

9.1.2. ligações de teclas para o comando screen

In a screen session, all keyboard inputs are sent to your

Page 494: Referências Debian

current window except for the command keystroke. All screen

command keystrokes are entered by typing ^A ("Control-A") plus a

single key [plus any parameters]. Here are important ones to

remember.

Tabela 9.2. Lista de ligações de teclas para o écran

┌─────────────┬────────────────────────────────────────────────┐

tecla de significado │ │ │

atalho │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A ? mostra um écran de ajuda (mostra as teclas de │ │ │

atalho) │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A c cria uma nova janela e muda para ela │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A n vai para a janela seguinte │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A p vai para a janela anterior │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A 0 vai para a janela número 0 │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A 1 vai para a janela número 1 │ │ │

├─────────────┼────────────────────────────────────────────────┤

Page 495: Referências Debian

^A w mostra uma lista de janelas │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A a envia Ctrl-A para a janela actual como entrada │ │ │

do teclado │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A h write a hardcopy of current window to file │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A H begin/end logging current window to file │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A ^X bloqueia o terminal (protegido por │ │ │

palavra-passe) │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A d separa a sessão do ecrã do terminal │ │ │

├─────────────┼────────────────────────────────────────────────┤

^A DD separa a sessão do ecrã e termina a sessão │ │ │

└─────────────┴────────────────────────────────────────────────┘

Veja screen(1) para detalhes.

9.2. Gravação de dados e apresentação

9.2.1. O daemon de log

Muitos programas registam as suas actividades sob o directório "

Page 496: Referências Debian

/var/log/".

O daemon de log do kernel: klogd(8)●

O daemon de log do sistema: syslogd(8)●

Veja Secção 3.5.9, “A mensagem do sistema” e Secção 3.5.10, “A

mensagem do kernel”.

9.2.2. Analizador de log

Aqui estão analisadores de logs notáveis

("~Gsecurity::log-analyzer" no aptitude(8)).

Tabela 9.3. Lista de analisadores de log do sistema

┌──────────────┬───────┬───────┬───────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

logwatch * V:3, 2592 analisador de log com saída │ │ │ │ │

I:3 bonita escrito em Perl │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

fail2ban * V:4, 660 banir IPs que causam erros de │ │ │ │ │

I:5 autenticação múltipla │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

analog * V:1.0, 4520 analisador de log do servidor │ │ │ │ │

I:16 web │ │ │ │ │

Page 497: Referências Debian

├──────────────┼───────┼───────┼───────────────────────────────┤

V:1.8, analisador de logs de servidor │ │ │ │ │

awstats * I:3 5200 web poderoso e cheio de │ │ │ │ │

funcionalidades │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

sarg * V:1.9, 644 squid analysis report generator│ │ │ │ │

I:2 │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

pflogsumm * V:0.3, 160 Postfix log entry summarizer │ │ │ │ │

I:0.7 │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

syslog-summary V:0.2, 84 sumariza o conteúdo do um │ │ │ │ │

* I:0.9 ficheiro de log do syslog │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

lire * V:0.15, 5304 full-featured log analyzer and │ │ │ │ │

I:0.17 report generator │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

fwlogwatch * V:0.10, 440 analisador de log da firewall │ │ │ │ │

I:0.2 │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

squidview * V:0.11, 244 monitor and analyze squid │ │ │ │ │

I:0.6 access.log files │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

visitors * V:0.09, 228 analisador de log do servidor │ │ │ │ │

Page 498: Referências Debian

I:0.3 web rápido │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

V:0.06, log file viewer with regexp │ │ │ │ │

swatch * I:0.2 112 matching, highlighting, and │ │ │ │ │

hooks │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

crm114 * V:0.06, 1300 Controllable Regex Mutilator │ │ │ │ │

I:0.18 and Spam Filter (CRM114) │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

icmpinfo * V:0.04, 84 interpretar mensagens ICMP │ │ │ │ │

I:0.2 │ │ │ │ │

└──────────────┴───────┴───────┴───────────────────────────────┘

Nota

CRM114 provides language infrastructure to write fuzzy filters

with the TRE regex library. Its popular use is spam mail filter

but it can be used as log analyzer.

9.2.3. Gravar as actividades da shell de modo limpo

O uso simples de script(1) (veja Secção 1.4.9, “Gravar as

actividades da shell”) para gravar a actividade da shell produz

um ficheiro com caracteres de controle. Isto pode ser evitado ao

usar o col(1) como o seguinte.

Page 499: Referências Debian

$ script

Script iniciado, ficheiro é typescript

Faça o que tem a fazer ... e carregue em Ctrl-D para terminar o

script.

$ col -bx <typescript >ficheiro_limpo

$ vim ficheiro_limpo

Se você não tem o script (por exemplo, durante o processo de

arranque no initramfs), então use antes o seguinte.

$ sh -i 2>&1 | tee typescript

Dica

Some x-terminal-emulator such as gnome-terminal can record. You

may wish to extend line buffer for scrollback.

Dica

You may use screen(1) with "^A H" (see Secção 9.1.2, “ligações

de teclas para o comando screen”) to perform recording of

console.

Dica

You may use emacs(1) with "M-x shell", "M-x eshell", or "M-x

term" to perform recording of console. You may later use "C-x

Page 500: Referências Debian

C-w" to write the buffer to a file.

9.2.4. Amostragem personalizada de dados em texto

Although pager tools such as more(1) and less(1) (see

Secção 1.4.5, “O pager”) and custom tools for highlighting and

formatting (see Secção 11.1.8, “Highlighting and formatting

plain text data”) can display text data nicely, general purpose

editors (see Secção 1.4.6, “O editor de texto”) are most

versatile and customizable.

Dica

For vim(1) and its pager mode alias view(1), ":set hls" enables

highlighted search.

9.2.5. Amostragem personalizada de hora e data

The default display format of time and date by the "ls -l"

command depends on the locale (see Secção 1.2.6, “Marcas

temporais (Timestamps)” for value). The "$LANG" variable is

referred first and it can be overridden by the "$LC_TIME"

variable.

The actual default display format for each locale depends on the

version of the standard C library (the libc6 package) used.

I.e., different releases of Debian had different defaults.

If you really wish to customize this display format of time and

Page 501: Referências Debian

date beyond the locale, you should set the time style value by

the "--time-style" argument or by the "$TIME_STYLE" value (see

ls(1), date(1), "info coreutils 'ls invocation'").

Tabela 9.4. Mostra exemplos de hora e data para o comando "ls

-l" para lenny

┌───────────────────┬─────────────┬────────────────────────────┐

valor do estilo de localização mostra a hora e data │ │ │ │

hora │ │ │ │

├───────────────────┼─────────────┼────────────────────────────┤

iso qualquer 01-19 00:15 │ │ │ │

├───────────────────┼─────────────┼────────────────────────────┤

long-iso qualquer 2009-01-19 00:15 │ │ │ │

├───────────────────┼─────────────┼────────────────────────────┤

full-iso qualquer 2009-01-19 │ │ │ │

00:15:16.000000000 +0900 │ │ │ │

├───────────────────┼─────────────┼────────────────────────────┤

locale C Jan 19 00:15 │ │ │ │

├───────────────────┼─────────────┼────────────────────────────┤

locale en_US.UTF-8 2009-01-19 00:15 │ │ │ │

├───────────────────┼─────────────┼────────────────────────────┤

locale es_ES.UTF-8 ene 19 00:15 │ │ │ │

├───────────────────┼─────────────┼────────────────────────────┤

Page 502: Referências Debian

+%d.%m.%y %H:%M qualquer 19.01.09 00:15 │ │ │ │

├───────────────────┼─────────────┼────────────────────────────┤

+%d.%b.%y %H:%M C ou 19.Jan.09 00:15 │ │ │ │

en_US.UTF-8 │ │ │ │

├───────────────────┼─────────────┼────────────────────────────┤

+%d.%b.%y %H:%M es_ES.UTF-8 19.ene.09 00:15 │ │ │ │

└───────────────────┴─────────────┴────────────────────────────┘

Dica

You can eliminate typing long option on commandline using

command alias, e.g. "alias ls='ls --time-style=+%d.%m.%y\

%H:%M'" (see Secção 1.5.9, “Command alias”).

Dica

ISO 8601 é seguido por estes formatos iso.

9.2.6. Echo de shell colorido

Shell echo to most modern terminals can be colorized using ANSI

escape code (see "/usr/share/doc/xterm/ctlseqs.txt.gz").

Por exemplo, tente o seguinte

$ RED=$(printf "\x1b[31m")

Page 503: Referências Debian

$ NORMAL=$(printf "\x1b[0m")

$ REVERSE=$(printf "\x1b[7m")

$ echo "${RED}RED-TEXT${NORMAL} ${REVERSE}REVERSE-TEXT${NORMAL}"

9.2.7. Comandos coloridos

Comandos coloridos são úteis para inspeccionar os seus

resultados no ambiente interactivo. Eu incluí o seguinte no meu

"~/.bashrc".

if [ "$TERM" != "dumb" ]; then

eval "`dircolors -b`"

alias ls='ls --color=always'

alias ll='ls --color=always -l'

alias la='ls --color=always -A'

alias less='less -R'

alias ls='ls --color=always'

alias grep='grep --color=always'

alias egrep='egrep --color=always'

alias fgrep='fgrep --color=always'

alias zgrep='zgrep --color=always'

else

alias ll='ls -l'

alias la='ls -A'

fi

The use of alias limits color effects to the interactive command

usage. It has advantage over exporting environment variable

"export GREP_OPTIONS='--color=auto'" since color can be seen

Page 504: Referências Debian

under pager programs such as less(1). If you wish to suppress

color when piping to other programs, use "--color=auto" instead

in the above example for "~/.bashrc".

Dica

You can turn off these colorizing aliases in the interactive

environment by invoking shell with "TERM=dumb bash".

9.2.8. Recordando as actividades do editor para repetições

complexas

Você pode recordar as actividades do editor para repetições

complexas.

Para o Vim, como se segue.

"qa": inicia a gravação de caracteres teclados no registo●

nomeado "a".

... actividades do editor●

"q": termina a gravação de caracteres escritos●

"@a": executa o conteúdo do registo "a".●

Para Emacs, como se segue

"C-x (": começa a definir uma macro de teclado.●

... actividades do editor●

"C-x )": termina de definir uma macro de teclado.●

"C-x e": executa uma macro de teclado.●

Page 505: Referências Debian

9.2.9. Gravar a imagem gráfica de uma aplicação X

There are few ways to record the graphic image of an X

application, including an xterm display.

Tabela 9.5. Lista de ferramentas gráficas de manipulação de

imagens

┌───────────────┬────────────┬───────┬─────────┐

pacote popcon tamanho comando │ │ │ │ │

├───────────────┼────────────┼───────┼─────────┤

xbase-clients * V:3, I:47 132 xwd(1) │ │ │ │ │

├───────────────┼────────────┼───────┼─────────┤

gimp * V:12, I:44 13560 Menu GUI │ │ │ │ │

├───────────────┼────────────┼───────┼─────────┤

imagemagick * V:13, I:35 268 import(1)│ │ │ │ │

├───────────────┼────────────┼───────┼─────────┤

scrot * V:0.3, I:1.4 80 scrot(1) │ │ │ │ │

└───────────────┴────────────┴───────┴─────────┘

9.2.10. Gravar alterações em ficheiros de configuração

Existem ferramentas especializadas para gravar alterações em

ficheiros de configuração com a ajuda do sistema DVCS.

Tabela 9.6. Lista de pacotes para gravar histórico de

configuração em VCS

Page 506: Referências Debian

┌───────────┬───────┬───────┬──────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├───────────┼───────┼───────┼──────────────────────────────────┤

V:1.0, store configuration files and │ │ │ │ │

etckeeper * I:1.5 376 their metadata with Git (default),│ │ │ │ │

Mercurial, or Bazaar (new) │ │ │ │ │

├───────────┼───────┼───────┼──────────────────────────────────┤

changetrack V:0.07, 152 armazenar ficheiros de │ │ │ │ │

* I:0.09 configuração com RCS (antigo) │ │ │ │ │

└───────────┴───────┴───────┴──────────────────────────────────┘

I recommend to use the etckeeper package with git(1) which put

entire "/etc" under VCS control. Its installation guide and

tutorial are found in "/usr/share/doc/etckeeper/README.gz".

Essentially, running "sudo etckeeper init" initializes the git

repository for "/etc" just like the process explained in

Secção 10.9.5, “Git para gravar o histórico de configuração” but

with special hook scripts for more thorough setups.

As you change your configuration, you can use git(1) normally to

record them. It automatically records changes nicely every time

you run package management commands, too.

Dica

Page 507: Referências Debian

You can browse the change history of "/etc" by executing "sudo

GIT_DIR=/etc/.git gitk" with clear view for new installed

packages, removed packages, and version changes of packages.

9.3. Dicas de armazenamento de dados

Booting your system with Linux live CDs or debian-installer CDs

in rescue mode make it easy for you to reconfigure data storage

on your boot device. See also Secção 10.3, “Os dados binários”.

9.3.1. Configuração das partições do disco

For disk partition configuration, although fdisk(8) has been

considered standard, parted(8) deserves some attention. "Disk

partitioning data", "partition table", "partition map", and

"disk label" are all synonyms.

Most PCs use the classic Master Boot Record (MBR) scheme to hold

disk partitioning data in the first sector, i.e., LBA sector 0

(512 bytes).

Nota

Some new PCs with Extensible Firmware Interface (EFI), including

Intel-based Macs, use GUID Partition Table (GPT) scheme to hold

disk partitioning data not in the first sector.

Apesar do fdisk(8) ter sido o standard como ferramenta de

Page 508: Referências Debian

particionamento de disco, o parted(8) está a substituí-lo.

Tabela 9.7. Lista de pacotes de gestão de partições do disco

┌──────────┬───────┬─────────┬─────────┬───────────────────────┐

pacote popcon tamanho GPT descrição │ │ │ │ │ │

├──────────┼───────┼─────────┼─────────┼───────────────────────┤

util-linux V:91, Não vários utilitários de │ │ │ │ │ │

* I:99 2216 suportado sistema incluindo fdisk│ │ │ │ │ │

(8) e cfdisk(8) │ │ │ │ │ │

├──────────┼───────┼─────────┼─────────┼───────────────────────┤

V:1.0, GNU Parted programa de │ │ │ │ │ │

parted * I:9 236 Suportado redimensionamento de │ │ │ │ │ │

partições do disco │ │ │ │ │ │

├──────────┼───────┼─────────┼─────────┼───────────────────────┤

V:3, Editor de partições do │ │ │ │ │ │

gparted * I:31 4548 Suportado GNOME baseado na │ │ │ │ │ │

libparted │ │ │ │ │ │

├──────────┼───────┼─────────┼─────────┼───────────────────────┤

V:0.10, Editor de partições do │ │ │ │ │ │

qtparted * I:0.9 NOT_FOUND Suportado KDE baseado na │ │ │ │ │ │

libparted │ │ │ │ │ │

├──────────┼───────┼─────────┼─────────┼───────────────────────┤

V:0.01, sincroniza a tabela de │ │ │ │ │ │

gptsync * I:0.18 72 Suportado partições MBR clássica │ │ │ │ │ │

Page 509: Referências Debian

com a GPT │ │ │ │ │ │

├──────────┼───────┼─────────┼─────────┼───────────────────────┤

programa para criar │ │ │ │ │ │

kpartx * V:1.0, 132 Suportado mapeamentos de │ │ │ │ │ │

I:1.8 dispositivo para │ │ │ │ │ │

partições │ │ │ │ │ │

└──────────┴───────┴─────────┴─────────┴───────────────────────┘

Cuidado

Although parted(8) claims to create and to resize filesystem

too, it is safer to do such things using best maintained

specialized tools such as mkfs(8) (mkfs.msdos(8), mkfs.ext2(8),

mkfs.ext3(8), …) and resize2fs(8).

Nota

In order to switch between GPT and MBR, you need to erase first

few blocks of disk contents directly (see Secção 10.3.6, “Limpar

conteúdo de ficheiro”) and use "parted /dev/sdx mklabel gpt" or

"parted /dev/sdx mklabel msdos" to set it. Please note "msdos"

is use here for MBR.

9.3.2. Aceder a partição usando UUID

Although reconfiguration of your partition or activation order

of removable storage media may yield different names for

Page 510: Referências Debian

partitions, you can access them consistently. This is also

helpful if you have multiple disks and your BIOS doesn't give

them consistent device names.

mount(8) com a opção "-U" pode montar um dispositivo de●

bloco usando o UUID, em vez de usar o seu nome de ficheiro

tal como "/dev/sda3".

"/etc/fstab" (veja fstab(5)) pode usar UUID.●

Os gestores de arranque (Secção 3.3, “Estágio 2: o gestor de●

arranque”) também podem usar UUID.

Dica

Você pode testar o UUID de um dispositivo especial de bloco com

blkid(8).

Dica

Device nodes of devices such as removable storage media can be

made static by using udev rules, if needed. See Secção 3.5.11,

“O sistema udev”.

9.3.3. Configuração do sistema de ficheiros

Para o sistema de ficheiro ext3, o pacote e2fsprogs

disponibiliza o seguinte.

mkfs.ext3(8) para criar um novo sistema de ficheiros ext3●

fsck.ext3(8) para verificar e reparar um sistema de●

Page 511: Referências Debian

ficheiros ext3 existente

tune2fs(8) para configurar o super-bloco do sistema de●

ficheiros ext3

Os comandos mkfs(8) e fsck(8) são disponibilizados pelo pacote

e2fsprogs como frontends para vários programas dependentes do

sistema de ficheiros (mkfs.fstype e fsck.fstype). Para o sistema

de ficheiros ext3 existem o mkfs.ext3(8) e o fsck.ext3(8) (estão

ligados por hardlink aos mke2fs(8) and e2fsck(8)).

Estão disponíveis comandos semelhantes para cada sistema de

ficheiros suportado pelo Linux.

Tabela 9.8. Lista de pacotes de gestão de sistemas de ficheiros

┌─────────────┬───────┬───────┬────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

e2fsprogs * V:60, 1924 utilitários para os sistemas de │ │ │ │ │

I:99 ficheiros ext2/ext3/ext4 │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

reiserfsprogs V:2, 1200 utilitários para o sistema de │ │ │ │ │

* I:8 ficheiros Reiserfs │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:3, utilitários para o sistema de │ │ │ │ │

dosfstools * I:31 192 ficheiros FAT. (Microsoft: │ │ │ │ │

MS-DOS, Windows) │ │ │ │ │

Page 512: Referências Debian

├─────────────┼───────┼───────┼────────────────────────────────┤

xfsprogs * V:2, 3272 utilitários para o sistema de │ │ │ │ │

I:10 ficheiros XFS. (SGI: IRIX) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:3, utilitários para o sistema de │ │ │ │ │

ntfsprogs * I:20 676 ficheiros NTFS. (Microsoft: │ │ │ │ │

Windows NT, …) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

jfsutils * V:0.5, 1112 utilitários para o sistema de │ │ │ │ │

I:2 ficheiros JFS. (IBM: AIX, OS/2) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

reiser4progs V:0.09, 1264 utilitários para o sistema de │ │ │ │ │

* I:0.7 ficheiros Reiser4 │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.06, utilitários para os sistemas de │ │ │ │ │

hfsprogs * I:0.8 316 ficheiros HFS e HFS Plus. │ │ │ │ │

(Apple: Mac OS) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

btrfs-tools * V:0.3, 1288 utilitários para o sistema de │ │ │ │ │

I:0.6 ficheiros btrfs │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.10, programa para zerar blocos │ │ │ │ │

zerofree * I:0.7 56 livres de sistemas de ficheiros │ │ │ │ │

ext2/3 │ │ │ │ │

Page 513: Referências Debian

└─────────────┴───────┴───────┴────────────────────────────────┘

Dica

Ext3 filesystem is the default filesystem for the Linux system

and strongly recommended to use it unless you have some specific

reasons not to. After Linux kernel 2.6.30 (Debian squeeze), ext4

filesystem is available and expected to be the default

filesystem for the Linux system. btrfs filesystem is expected to

be the next default filesystem after ext4 filesystem for the

Linux system.

Atenção

You might face some limitations with ext4 since it is new. For

example, you must have Linux kernel 2.6.30 or later if you wish

to resize an ext4 partition.

Dica

Algumas ferramentas permitem acesso a sistemas de ficheiros sem

suporte do kernel do Linux (veja Secção 10.3.2, “Manipular

ficheiros sem montar o disco”).

9.3.4. Criação do sistema de ficheiros e verificação de

integridade

Page 514: Referências Debian

The mkfs(8) command creates the filesystem on a Linux system.

The fsck(8) command provides the filesystem integrity check and

repair on a Linux system.

Cuidado

Geralmente não é seguro correr o fsck em sistemas de ficheiros

montados.

Dica

Verifique os ficheiros em "/var/log/fsck/" para os resultados do

comando fsck(8) executado a partir do script de arranque.

Dica

Use "shutdown -F -r now" para forçar a execução do comando fsck

(8) em segurança em todos os sistemas de ficheiros incluindo o

sistema de ficheiros raiz ao reiniciar a máquina. Veja o manual

do shutdown(8) para mais detalhes.

9.3.5. Optimização do sistema de ficheiros por opções de

montagem

A performance e características de um sistema de ficheiros pode

ser optimizada pelas opções de montagem usadas (veja fstab(5) e

mount(8)). As mais notáveis são as seguintes.

A opção "defaults" implica opções predefinidas:●

Page 515: Referências Debian

"rw,suid,dev,exec,auto,nouser,async". (geral)

A opção "noatime" ou "relatime" é muito eficaz para acelerar●

o acesso de leitura. (geral)

A opção "user" permite que um utilizador normal monte o●

sistema de ficheiros. Esta opção implica a combinação com a

opção "noexec,nosuid,nodev". (geral, usada para CDs e

disquetes)

A combinação de opções "noexec,nodev,nosuid" é usada para●

melhorar a segurança. (geral)

A opção "noauto" limita a montagem apenas por operação●

explícita. (geral)

A opção "data=journal" para ext3fs pode melhorar a●

integridade dos dados contra falhas de energia com alguma

perda na velocidade de gravação.

Dica

You need to provide kernel boot parameter (see Secção 3.3,

“Estágio 2: o gestor de arranque”), e.g. "rootflags=data=

journal" to deploy a non-default journaling mode for the root

filesystem. For lenny, the default jounaling mode is "rootflags=

data=ordered". For squeeze, it is "rootflags=data=writeback".

9.3.6. Optimização do sistema de ficheiros através do superblock

As características de um sistema de ficheiros podem ser

optimizadas via o seu super-bloco usando o comando tune2fs(8).

A execução de "sudo tune2fs -l /dev/hda1" mostra o conteúdo●

Page 516: Referências Debian

do super-bloco do sistema de ficheiros em "/dev/hda1".

A execução de "sudo tune2fs -c 50 /dev/hda1" muda a●

frequência das verificações do sistema de ficheiros

(execução do fsck durante o arranque) para cada 50 arranques

em "/dev/hda1".

Execution of "sudo tune2fs -j /dev/hda1" adds journaling●

capability to the filesystem, i.e. filesystem conversion

from ext2 to ext3 on "/dev/hda1". (Do this on the unmounted

filesystem.)

Execution of "sudo tune2fs -O extents,uninit_bg,dir_index /●

dev/hda1 && fsck -pf /dev/hda1" converts it from ext3 to

ext4 on "/dev/hda1". (Do this on the unmounted filesystem.)

Atenção

Filesystem conversion for the boot device to the ext4 filesystem

should be avoided until GRUB boot loader supports the ext4

filesystem well and installed Linux Kernel version is newer than

2.6.30.

Dica

Apesar do seu nome, o tune2fs(8) não funciona apenas no sistema

de ficheiros ext2, mas também nos sistemas de ficheiros ext3 e

ext4.

9.3.7. Optimização do disco rijo

Atenção

Page 517: Referências Debian

Please check your hardware and read manpage of hdparam(8) before

playing with hard disk configuration because this may be quite

dangerous for the data integrity.

You can test disk access speed of a hard disk, e.g. "/dev/hda",

by "hdparm -tT /dev/hda". For some hard disk connected with (E)

IDE, you can speed it up with "hdparm -q -c3 -d1 -u1 -m16 /dev/

hda" by enabling the "(E)IDE 32-bit I/O support", enabling the

"using_dma flag", setting "interrupt-unmask flag", and setting

the "multiple 16 sector I/O" (dangerous!).

Você pode testar a funcionalidade de cache de escrita de um

disco rijo, por exemplo "/dev/sda", com "hdparm -W /dev/sda".

Você pode desactivar a sua funcionalidade de cache de escrita

com "hdparm -W 0 /dev/sda".

You may be able to read badly pressed CDROMs on modern high

speed CD-ROM drive by slowing it down with "setcd -x 2".

9.3.8. Usar SMART para prever falhas no disco rijo

You can monitor and log your hard disk which is compliant to

SMART with the smartd(8) daemon.

1. Activar a função SMART na BIOS.

2. instalar o pacote smartmontools

3. Identificar os seus discos rijos al listá-los com df(1).

Page 518: Referências Debian

Vamos assumir uma drive de disco rijo a ser monitorizada●

como "/dev/hda".

4. Verifique o resultado de "smartctl -a /dev/hda" para ver se

a funcionalidade SMART está ligada actualmente.

Se não, active-o com "smartctl -s on -a /dev/hda".●

5. Active o daemon smartd(8) a correr com o seguinte.

retire a marca de comentário na linha "start_smartd=yes"●

no ficheiro "/etc/default/smartmontools"

reinicie o daemon smartd(8) com "sudo /etc/init.d/●

smartmontools restart".

Dica

O daemon smartd(8) pode ser personalizado com o ficheiro /etc/

smartd.conf incluindo em como ser notificado de avisos.

9.3.9. Expandir o espaço de armazenamento utilizável via LVM

For partitions created on Logical Volume Manager (LVM) (Linux

feature) at install time, they can be resized easily by

concatenating extents onto them or truncating extents from them

over multiple storage devices without major system

reconfiguration.

Cuidado

Deployment of the current LVM system may degrade guarantee

Page 519: Referências Debian

against filesystem corruption offered by journaled filesystems

such as ext3fs unless their system performance is sacrificed by

disabling write cache of hard disk.

9.3.10. Expandir o espaço de armazenamento utilizável ao montar

outra partição

If you have an empty partition (e.g., "/dev/sdx"), you can

format it with mkfs.ext3(1) and mount(8) it to a directory where

you need more space. (You need to copy original data contents.)

$ sudo mv work-dir old-dir

$ sudo mkfs.ext3 /dev/sdx

$ sudo mount -t ext3 /dev/sdx work-dir

$ sudo cp -a old-dir/* work-dir

$ sudo rm -rf old-dir

Dica

You may alternatively mount an empty disk image file (see

Secção 10.2.5, “Criar um ficheiro de imagem de disco vazio”) as

a loop device (see Secção 10.2.3, “Montar o ficheiro de imagem

de disco”). The actual disk usage grows with the actual data

stored.

9.3.11. Expandir o espaço de armazenamento utilizável usando

links simbólicos

If you have an empty directory (e.g., "/path/to/emp-dir") in

Page 520: Referências Debian

another partition with usable space, you can create a symlink to

the directory with ln(8).

$ sudo mv work-dir old-dir

$ sudo mkdir -p /path/to/emp-dir

$ sudo ln -sf /path/to/emp-dir work-dir

$ sudo cp -a old-dir/* work-dir

$ sudo rm -rf old-dir

Cuidado

Alguns softwares podem não funcionar bem com "links simbólicos

para directórios".

9.3.12. Expandir o espaço de armazenamento utilizável usando

aufs

If you have usable space in another partition (e.g., "/path/to/

"), you can create a directory in it and stack that on to a

directory where you need space with aufs.

$ sudo mv work-dir old-dir

$ sudo mkdir work-dir

$ sudo mkdir -p /path/to/emp-dir

$ sudo mount -t aufs -o br:/path/to/emp-dir:old-dir none work-dir

Cuidado

Use of aufs for long term data storage is not good idea since it

Page 521: Referências Debian

is under development and its design change may introduce issues.

Dica

In order to use aufs, its utility package aufs-tools and kernel

module package for aufs such as aufs-modules-2.6-amd64 need to

be installed.

Dica

aufs is used to provide writable root filesystem by many modern

live CD projects.

9.4. Dicas de encriptação de dados

With physical access to your PC, anyone can easily gain root

privilege and access all the files on your PC (see Secção 4.7.4,

“Tornar a palavra-passe do root segura”). This means that login

password system can not secure your private and sensitive data

against possible theft of your PC. You must deploy data

encryption technology to do it. Although GNU privacy guard (see

Secção 10.4, “Infraestrutura da segurança de dados”) can encrypt

files, it takes some user efforts.

dm-crypt and eCryptfs facilitates automatic data encryption

natively via Linux kernel modules with minimal user efforts.

Tabela 9.9. Lista de utilitários de encriptação de dados

Page 522: Referências Debian

┌──────────────┬──────┬───────┬────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├──────────────┼──────┼───────┼────────────────────────────────┤

cryptsetup * V:3, 1172 utilities for encrypted block │ │ │ │ │

I:5 device (dm-crypt / LUKS) │ │ │ │ │

├──────────────┼──────┼───────┼────────────────────────────────┤

utilities for encrypted block │ │ │ │ │

cryptmount * V:0.2, 360 device (dm-crypt / LUKS) with │ │ │ │ │

I:0.5 focus on mount/unmount by normal│ │ │ │ │

users │ │ │ │ │

├──────────────┼──────┼───────┼────────────────────────────────┤

ecryptfs-utils V:0.2, 416 utilities for encrypted stacked │ │ │ │ │

* I:0.3 filesystem (eCryptfs) │ │ │ │ │

└──────────────┴──────┴───────┴────────────────────────────────┘

Dm-crypt is a cryptographic filesystem using device-mapper.

Device-mapper maps one block device to another.

eCryptfs is another cryptographic filesystem using stacked

filesystem. Stacked filesystem stacks itself on top of an

existing directory of a mounted filesystem.

Cuidado

A encriptação de dados custa tempo da CPU e etc. Por favor pese

Page 523: Referências Debian

os seus benefícios e custos.

Nota

Entire Debian system can be installed on a encrypted disk by the

debian-installer (lenny or newer) using dm-crypt/LUKS and

initramfs.

Dica

Veja Secção 10.4, “Infraestrutura da segurança de dados” para

utilitário de encriptação do espaço de utilizador: GNU Privacy

Guard.

9.4.1. Encriptação de discos amovíveis com dm-crypt/LUKS

You can encrypt contents of removable mass devices, e.g. USB

memory stick on "/dev/sdx", using dm-crypt/LUKS. You simply

formatting it as the following.

# badblocks -c 10240 -s -w -t random -v /dev/sdx

# shred -v -n 1 /dev/sdx

# fdisk /dev/sdx

... "n" "p" "1" "return" "return" "w"

# cryptsetup luksFormat /dev/sdx1

...

# cryptsetup luksOpen /dev/sdx1 sdx1

...

# ls -l /dev/mapper/

Page 524: Referências Debian

total 0

crw-rw---- 1 root root 10, 60 2008-10-04 18:44 control

brw-rw---- 1 root disk 254, 0 2008-10-04 23:55 sdx1

# mkfs.vfat /dev/mapper/sdx1

...

# cryptsetup luksClose sdx1

Then, it can be mounted just like normal one on to "/media/

<disk_label>", except for asking password (see Secção 10.1.10,

“Dispositivo de armazenamento amovível”) under modern desktop

environment, such as GNOME using gnome-mount(1). The difference

is that every data written to it is encrypted. You may

alternatively format media in different file format, e.g., ext3

with "mkfs.ext3 /dev/sdx1".

Nota

Se você é realmente paranóico pela segurança dos dados, pode

precisar de sobrescrever várias vezes no exemplo em cima. No

entanto esta operação irá consumir muito tempo.

9.4.2. Partição swap encriptada com dm-crypt

Vamos assumir que o seu "/etc/fstab" original contém o seguinte.

/dev/sda7 swap sw 0 0

Você pode activar a encriptação da partição swap usando o

dm-crypt com o seguinte.

Page 525: Referências Debian

# aptitude install cryptsetup

# swapoff -a

# echo "cswap /dev/sda7 /dev/urandom swap" >> /etc/crypttab

# perl -i -p -e "s/\/dev\/sda7/\/dev\/mapper\/cswap/" /etc/fstab

# /etc/init.d/cryptdisks restart

...

# swapon -a

9.4.3. Encriptar ficheiro automaticamente com eCryptfs

Você pode encriptar ficheiros escritos sob "~/Private/"

automaticamente usando eCryptfs e o pacote ecryptfs-utils.

Execute ecryptfs-setup-private(1) e configure "~/Private/"●

pelos seguintes avisos.

Active "~/Private/" ao executar ecryptfs-mount-private(1).●

Move ficheiros de dados sensitivos para "~/Private/" e cria●

os links simbólicos necessários.

Candidatos: "~/.fetchmailrc", "~/.ssh/identity", "~/.ssh○

/id_rsa", "~/.ssh/id_dsa" e outros ficheiros com

"go-rwx"

Move directórios de dados sensitivos para um sub-directório●

em "~/Private/" e cria os links simbólicos necessários.

Candidatos: "~/.gnupg" e outros directórios com "go-rwx"○

Crie um link simbólico de "~/Desktop/Private/" para "~/●

Private/" para facilitar as operações do ambiente de

Page 526: Referências Debian

trabalho.

Desactive "~/Private/" ao executar ecryptfs-umount-private●

(1).

Active "~/Private/" ao emitir "ecryptfs-mount-private"●

quando necessitar de dados encriptados.

Dica

Since eCryptfs selectively encrypt only the sensitive files, its

system cost is much less than using dm-crypt on the entire root

or "/home" device. It does not require any special on-disk

storage allocation effort but cannot keep all filesystem

metadata confidential.

9.4.4. Montar eCryptfs automaticamente

If you use your login password for wrapping encryption keys, you

can automate mounting eCryptfs via PAM (Pluggable Authentication

Modules).

Insira a seguinte linha mesmo antes de "pam_permit.so" em "/etc/

pam.d/common-auth".

auth required pam_ecryptfs.so unwrap

Insira a seguinte linha mesmo na última linha em "/etc/pam.d/

common-session".

session optional pam_ecryptfs.so unwrap

Page 527: Referências Debian

Insira a seguinte linha na primeira linha activa em "/etc/pam.d/

common-password".

password required pam_ecryptfs.so

Isto é bastante conveniente.

Atenção

Erros de configuração do PAM podem bloqueá-lo fora do seu

próprio sistema. Veja Capítulo 4, Autenticação.

Cuidado

If you use your login password for wrapping encryption keys,

your encrypted data are as secure as your user login password

(see Secção 4.3, “Boa palavra-passe”). Unless you are careful to

set up a strong password, your data is at risk when someone runs

password cracking software after stealing your laptop (see

Secção 4.7.4, “Tornar a palavra-passe do root segura”).

9.5. Monitorizar, controlar e arrancar as actividades de

programas

As actividades de programas podem ser monitorizadas e

controladas usando ferramentas especiais

Tabela 9.10. Lista de ferramentas para monitorizar e controlar

Page 528: Referências Debian

as actividades de programas

┌─────────┬───────┬───────┬────────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

coreutils V:92, 13828 nice(1): correr um programa com │ │ │ │ │

* I:99 prioridade de agendamento modificada│ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

bsdutils V:77, renice(1): modifica a prioridade de │ │ │ │ │

* I:99 196 agendamento de um processo em │ │ │ │ │

execução │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

V:86, "/proc" utilitários de sistema de │ │ │ │ │

procps * I:99 772 ficheiros: ps(1), top(1), kill(1) , │ │ │ │ │

watch(1), … │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

V:47, "/proc" utilitários de sistema de │ │ │ │ │

psmisc * I:88 716 ficheiros: killall(1), fuser(1), │ │ │ │ │

peekfd(1), pstree(1) │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

V:6, time(1): run a program to report │ │ │ │ │

time * I:84 152 system resource usages with respect │ │ │ │ │

to time │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

V:4, sar(1), iostat(1), mpstat(1), …: │ │ │ │ │

Page 529: Referências Debian

sysstat * I:9 872 ferramentas de performance do │ │ │ │ │

sistema para Linux │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

isag * V:0.07, 152 Interactive System Activity Grapher │ │ │ │ │

I:0.4 para sysstat │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

V:16, lsof(8): lista os ficheiro abertos │ │ │ │ │

lsof * I:90 444 por um processo em execução usando a│ │ │ │ │

opção "-p" │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

strace * V:5, 396 strace(1): rastreia chamadas e │ │ │ │ │

I:39 sinais do sistema │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

ltrace * V:0.3, 188 ltrace(1): rastreia chamadas de │ │ │ │ │

I:2 bibliotecas │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

xtrace * V:0.02, 372 xtrace(1): rastreia a comunicação │ │ │ │ │

I:0.18 entre cliente X11 e servidor │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

powertop V:0.7, powertop(1): informação sobre │ │ │ │ │

* I:12 524 sistema de energia usado em │ │ │ │ │

portáteis baseados em Intel │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

V:91, run processes according to a │ │ │ │ │

cron * I:99 240 schedule in background from cron(8) │ │ │ │ │

Page 530: Referências Debian

daemon │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

V:41, agenda de comandos tipo cron para │ │ │ │ │

anacron * I:44 120 sistemas que não funcionam 24 horas │ │ │ │ │

por dia │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

V:50, at(1) or batch(1): run a job at a │ │ │ │ │

at * I:83 220 specified time or below certain load│ │ │ │ │

level │ │ │ │ │

└─────────┴───────┴───────┴────────────────────────────────────┘

Dica

Os pacotes procps disponibilizam as bases de monitorizar,

controlar e iniciar actividades de programas. Você deve

aprendê-las todas.

9.5.1. Temporizando um processo

Display time used by the process invoked by the command.

# time some_command >/dev/null

real 0m0.035s # time on wall clock (elapsed real time)

user 0m0.000s # time in user mode

sys 0m0.020s # time in kernel mode

Page 531: Referências Debian

9.5.2. A prioridade de agendamento

Um valor nice é usado para controlar a prioridade de agendamento

para o processo.

Tabela 9.11. Lista de valores nice para a prioridade de

agendamento

┌───────────┬──────────────────────────────────────────────────┐

o valor prioridade de agendamento │ │ │

nice │ │ │

├───────────┼──────────────────────────────────────────────────┤

19 processo de prioridade menor (nice) │ │ │

├───────────┼──────────────────────────────────────────────────┤

0 processo de prioridade muito alta para o │ │ │

utilizador │ │ │

├───────────┼──────────────────────────────────────────────────┤

-20 processo de prioridade muito alta para o root │ │ │

(não-nice) │ │ │

└───────────┴──────────────────────────────────────────────────┘

# nice -19 top # muito bom

# nice --20 wodim -v -eject speed=2 dev=0,0 disk.img # muito rápido

Sometimes an extreme nice value does more harm than good to the

Page 532: Referências Debian

system. Use this command carefully.

9.5.3. O comando ps

The ps(1) command on the Debian support both BSD and SystemV

features and helps to identify the process activity statically.

Tabela 9.12. Lista dos estilos do comando ps

┌─────────┬──────────────┬────────────────┐

estilo comando típico funcionalidade │ │ │ │

├─────────┼──────────────┼────────────────┤

BSD ps aux mostra %CPU %MEM│ │ │ │

├─────────┼──────────────┼────────────────┤

Sistema V ps -efH mostra PPID │ │ │ │

└─────────┴──────────────┴────────────────┘

For the zombie (defunct) children process, you can kill them by

the parent process ID identified in the "PPID" field.

O comando pstree(1) mostra uma árvore de processos.

9.5.4. O comando top

top(1) on the Debian has rich features and helps to identify

what process is acting funny dynamically.

Tabela 9.13. Lista de comandos para o top

Page 533: Referências Debian

┌─────────────┬────────────────────────────────────┐

tecla comando descrição da resposta │ │ │

├─────────────┼────────────────────────────────────┤

h ou ? mostrar ajuda │ │ │

├─────────────┼────────────────────────────────────┤

f define/redefine o campo do mostrador│ │ │

├─────────────┼────────────────────────────────────┤

o reorganiza o campo do mostrador │ │ │

├─────────────┼────────────────────────────────────┤

F define a ordem de campo de chave │ │ │

├─────────────┼────────────────────────────────────┤

k mata um processo │ │ │

├─────────────┼────────────────────────────────────┤

r faz renice a um processo │ │ │

├─────────────┼────────────────────────────────────┤

q sair do comando top │ │ │

└─────────────┴────────────────────────────────────┘

9.5.5. Listar ficheiros abertos por um processo

You can list all files opened by a process with a process ID

(PID), e.g. 1, by the following.

$ sudo lsof -p 1

PID=1 is usually init program.

Page 534: Referências Debian

9.5.6. Rastear as actividades de programas

You can trace program activity with strace(1), ltrace(1), or

xtrace(1) for system calls and signals, library calls, or

communication between X11 client and server.

You can trace system calls of the ls command as the following.

$ sudo strace ls

9.5.7. Identificação de um processo usando ficheiros ou sockets

You can also identify processes using files by fuser(1), e.g.

for "/var/log/mail.log" by the following.

$ sudo fuser -v /var/log/mail.log

USER PID ACCESS COMMAND

/var/log/mail.log: root 2946 F.... syslogd

You see that file "/var/log/mail.log" is open for writing by the

syslogd(8) command.

You can also identify processes using sockets by fuser(1), e.g.

for "smtp/tcp" by the following.

$ sudo fuser -v smtp/tcp

USER PID ACCESS COMMAND

smtp/tcp: Debian-exim 3379 F.... exim4

Page 535: Referências Debian

Now you know your system runs exim4(8) to handle TCP connections

to SMTP port (25).

9.5.8. Repetir um comando com um intervalo constante

watch(1) executes a program repeatedly with a constant interval

while showing its output in fullscreen.

$ watch w

This displays who is logged on to the system updated every 2

seconds.

9.5.9. Repeating a command looping over files

There are several ways to repeat a command looping over files

matching some condition, e.g. matching glob pattern "*.ext".

Shell for-loop method (see Secção 12.1.4, “Ciclos da shell”●

):

for x in *.ext; do if [ -f "$x"]; then command "$x" ; fi; done

find(1) and xargs(1) combination:●

find . -type f -maxdepth 1 -name '*.ext' -print0 | xargs -0 -n 1 command

find(1) with "-exec" option with a command:●

Page 536: Referências Debian

find . -type f -maxdepth 1 -name '*.ext' -exec command '{}' \;

find(1) with "-exec" option with a short shell script:●

find . -type f -maxdepth 1 -name '*.ext' -exec sh -c "command '{}' && echo 'successful'" \;

The above examples are written to ensure proper handling of

funny file names such as ones containing spaces. See

Secção 10.1.5, “Idiomas para a selecção de ficheiros” for more

advance uses of find(1).

9.5.10. Arrancar um programa a partir da GUI

You can set up to start a process from graphical user interface

(GUI).

Under GNOME desktop environment, a program can be started with

proper argument by double-clicking the launcher icon, by

drag-and-drop of a file icon to the launcher icon, or by "Open

with …" menu via right clicking a file icon. KDE can do the

equivalent, too.

Here is an example under GNOME to create a launcher icon for mc

(1) started in gnome-terminal(1).

Crie um programa executável "mc-term" com o seguinte.

# cat >/usr/local/bin/mc-term <<EOF

Page 537: Referências Debian

#!/bin/sh

gnome-terminal -e "mc \$1"

EOF

# chmod 755 /usr/local/bin/mc-term

Crie um lançador de ambiente de trabalho com o seguinte.

1. Right click desktop space to select "Create Launcher …".

2. Defina "Tipo" para "Aplicação".

3. Defina "Nome" para "mc".

4. Defina "Comando" para "mc-term %f"

5. Clique "OK".

Crie uma associação de 'abrir com' como o seguinte.

1. Right click folder to select "Open with Other Application

…".

2. Click open "Use a custom command" dialog and enter "mc-term

%f".

3. Clique "Abrir"

Dica

Launcher is a file at "~/Desktop" with ".desktop" as its

extension.

9.5.11. Personalizar o programa a ser arrancado

Some programs start another program automatically. Here are

Page 538: Referências Debian

check points for customizing this process.

Menu de configuração da aplicação:●

Ambiente GNOME: "Sistema" → "Preferências" → "Aplicação○

Preferida"

KDE desktop: "K" → "Control Center" → "KDE Components" →○

"Component Chooser"

Navegador Iceweasel: "Editar" → "Preferências" →○

"Aplicações"

mc(1): "/etc/mc/mc.ext"○

Environment variables such as "$BROWSER", "$EDITOR",●

"$VISUAL", and "$PAGER" (see eviron(7))

The update-alternatives(8) system for programs such as●

"editor", "view", "x-www-browser", "gnome-www-browser", and

"www-browser" (see Secção 1.4.7, “Definir um editor de texto

predefinido”)

the "~/.mailcap" and "/etc/mailcap" file contents which●

associate MIME type with program (see mailcap(5))

The "~/.mime.types" and "/etc/mime.types" file contents●

which associate file name extension with MIME type (see

run-mailcap(1))

Dica

update-mime(8) updates the "/etc/mailcap" file using "/etc/

mailcap.order" file (see mailcap.order(5)).

Dica

Page 539: Referências Debian

The debianutils package provides sensible-browser(1),

sensible-editor(1), and sensible-pager(1) which make sensible

decisions on which editor, pager, and web browser to call,

respectively. I recommend you to read these shell scripts.

Dica

In order to run a console application such as mutt under X as

your preferred application, you should create an X application

as following and set "/usr/local/bin/mutt-term" as your

preferred application to be started as described.

# cat /usr/local/bin/mutt-term <<EOF

#!/bin/sh

gnome-terminal -e "mutt \$@"

EOF

chmod 755 /usr/local/bin/mutt-term

9.5.12. Matar um processo

Use kill(1) to kill (or send a signal to) a process by the

process ID.

Use killall(1) or pkill(1) to do the same by the process command

name and other attributes.

Tabela 9.14. Lista dos sinais frequentemente usados para matar

comandos

Page 540: Referências Debian

┌──────────────┬─────────────┬────────────────┐

valor do sinal nome do sinal função │ │ │ │

├──────────────┼─────────────┼────────────────┤

1 HUP reiniciar daemon│ │ │ │

├──────────────┼─────────────┼────────────────┤

15 TERM morte normal │ │ │ │

├──────────────┼─────────────┼────────────────┤

9 KILL morte forçada │ │ │ │

└──────────────┴─────────────┴────────────────┘

9.5.13. Scheduling tasks once

Run the at(1) command to schedule a one-time job by the

following.

$ echo 'command -args'| at 3:40 monday

9.5.14. Scheduling tasks regularly

Use cron(8) to schedule tasks regularly. See crontab(1) and

crontab(5).

If you are a member of crontab group, you can schedule to run

processes as a normal user, e.g. foo by creating a crontab(5)

file as "/var/spool/cron/crontabs/foo" with "crontab -e"

command.

Page 541: Referências Debian

Aqui está um exemplo de um ficheiro crontab(5).

# use /bin/sh to run commands, no matter what /etc/passwd says

SHELL=/bin/sh

# mail any output to paul, no matter whose crontab this is

MAILTO=paul

# Min Hour DayOfMonth Month DayOfWeek command (Day... are OR'ed)

# run at 00:05, every day

5 0 * * * $HOME/bin/daily.job >> $HOME/tmp/out 2>&1

# run at 14:15 on the first of every month -- output mailed to paul

15 14 1 * * $HOME/bin/monthly

# run at 22:00 on weekdays(1-5), annoy Joe. % for newline, last % for cc:

0 22 * * 1-5 mail -s "It's 10pm" joe%Joe,%%Where are your kids?%.%%

23 */2 1 2 * echo "run 23 minutes after 0am, 2am, 4am ..., on Feb 1"

5 4 * * sun echo "run at 04:05 every Sunday"

# run at 03:40 on the first Monday of each month

40 3 1-7 * * [ "$(date +%a)" == "Mon" ] && command -args

Dica

For the system not running continuously, install the anacron

package to schedule periodic commands at the specified intervals

as closely as machine-uptime permits. See anacron(8) and

anacrontab(5).

Dica

For scheduled system maintenance scripts, you can run them

periodically from root account by placing such scripts in "/etc/

Page 542: Referências Debian

cron.hourly/", "/etc/cron.daily/", "/etc/cron.weekly/", or "/etc

/cron.monthly/". Execution timings of these scripts can be

customized by "/etc/crontab" and "/etc/anacrontab".

9.5.15. Tecla Alt-SysRq

Insurance against system malfunction is provided by the kernel

compile option "Magic SysRq key" (SAK key) which is now the

default for the Debian kernel. Pressing Alt-SysRq followed by

one of the following keys does the magic of rescuing control of

the system.

Tabela 9.15. Lista de teclas de comando SAK

┌──────────────────┬───────────────────────────────────────────┐

key following descrição da acção │ │ │

Alt-SysRq │ │ │

├──────────────────┼───────────────────────────────────────────┤

r restore the keyboard from raw mode after X │ │ │

crashes │ │ │

├──────────────────┼───────────────────────────────────────────┤

0 change the console loglevel to 0 to reduce │ │ │

error messages │ │ │

├──────────────────┼───────────────────────────────────────────┤

k kill all processes on the current virtual │ │ │

console │ │ │

Page 543: Referências Debian

├──────────────────┼───────────────────────────────────────────┤

e send a SIGTERM to all processes, except for│ │ │

init(8) │ │ │

├──────────────────┼───────────────────────────────────────────┤

i send a SIGKILL to all processes, except for│ │ │

init(8) │ │ │

├──────────────────┼───────────────────────────────────────────┤

s sync all mounted filesystems │ │ │

├──────────────────┼───────────────────────────────────────────┤

u remount all mounted filesystems read-only (│ │ │

umount) │ │ │

├──────────────────┼───────────────────────────────────────────┤

b reboot the system without syncing or │ │ │

unmounting │ │ │

└──────────────────┴───────────────────────────────────────────┘

The combination of "Alt-SysRq s", "Alt-SysRq u", and "Alt-SysRq

r" is good for getting out of really bad situations.

See "/usr/share/doc/linux-doc-2.6.*/Documentation/sysrq.txt.gz".

Cuidado

The Alt-SysRq feature may be considered a security risk by

Page 544: Referências Debian

allowing users access to root-privileged functions. Placing

"echo 0 >/proc/sys/kernel/sysrq" in "/etc/rc.local" or

"kernel.sysrq = 0" in "/etc/sysctl.conf" disables the Alt-SysRq

feature.

Dica

From SSH terminal etc., you can use the Alt-SysRq feature by

writing to the "/proc/sysrq-trigger". For example, "echo s > /

proc/sysrq-trigger; echo u > /proc/sysrq-trigger" from the root

shell prompt syncs and umounts all mounted filesystems.

9.6. Dicas de manutenção do sistema

9.6.1. Quem está no sistema?

Você pode verificar quem está no sistema com o seguinte.

who(1) mostra quem tem sessão iniciada.●

w(1) mostra quem tem sessão iniciada e o que estão a fazer.●

last(1) mostra listagem do último utilizador a iniciar●

sessão.

lastb(1 )mostra listagem dos últimos utilizadores a falharem●

o inicio de sessão.

Dica

"/var/run/utmp", "/var/log/wtmp", e "/var/run/utmp" detém tal

informação do utilizador. Veja login(1) e utmp(5).

Page 545: Referências Debian

9.6.2. Avisar todos

Você pode mandar uma mensagem para todos os que têm sessão

iniciada no sistema com wall(1) com o seguinte.

$ echo "Vamos desligar dentro de 1 hora" | wall

9.6.3. Identificação do hardware

For the PCI-like devices (AGP, PCI-Express, CardBus, ExpressCard

, etc.), lspci(8) (probably with "-nn" option) is a good start

for the hardware identification

Alternatively, you can identify the hardware by reading contents

of "/proc/bus/pci/devices" or browsing directory tree under "/

sys/bus/pci" (see Secção 1.2.12, “procfs e sysfs”).

Tabela 9.16. Lista de ferramenta de identificação de hardware

┌───────────┬────────┬───────┬─────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├───────────┼────────┼───────┼─────────────────────────────────┤

pciutils * V:15, 908 Utilitários PCI do Linux: lspci │ │ │ │ │

I:92 (8) │ │ │ │ │

├───────────┼────────┼───────┼─────────────────────────────────┤

usbutils * V:38, 604 Utilitários USB do Linux: lsusb │ │ │ │ │

Page 546: Referências Debian

I:97 (8) │ │ │ │ │

├───────────┼────────┼───────┼─────────────────────────────────┤

pcmciautils V:0.8, 100 Utilitários PCMCIA par Linux 2.6:│ │ │ │ │

* I:13 pccardctl(8) │ │ │ │ │

├───────────┼────────┼───────┼─────────────────────────────────┤

V:0.18, colecção de ferramentas para │ │ │ │ │

scsitools * I:1.1 484 gestão de hardware SCSI: lsscsi │ │ │ │ │

(8) │ │ │ │ │

├───────────┼────────┼───────┼─────────────────────────────────┤

pnputils * V:0.01, 108 Utilitários Plug and Play da │ │ │ │ │

I:0.16 BIOS: lspnp(8) │ │ │ │ │

├───────────┼────────┼───────┼─────────────────────────────────┤

procinfo * V:0.3, 164 informação do sistema obtida de "│ │ │ │ │

I:3 /proc": lsdev(8) │ │ │ │ │

├───────────┼────────┼───────┼─────────────────────────────────┤

lshw * V:1.2, 604 informação acerca da configuração│ │ │ │ │

I:7 do hardware: lshw(1) │ │ │ │ │

├───────────┼────────┼───────┼─────────────────────────────────┤

discover * V:2, 120 sistema de identificação de │ │ │ │ │

I:15 hardware: discover(8) │ │ │ │ │

└───────────┴────────┴───────┴─────────────────────────────────┘

9.6.4. Configuração do hardware

Page 547: Referências Debian

Although most of the hardware configuration on modern GUI

desktop systems such as GNOME and KDE can be managed through

accompanying GUI configuration tools, it is a good idea to know

some basics methods to configure them.

Tabela 9.17. Lista de ferramentas de configuração do hardware

┌─────────────────┬───────┬───────┬────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

hal * V:37, 1668 Hardware Abstraction Layer: │ │ │ │ │

I:49 lshal(1) │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

console-tools * V:47, 956 Linux console font and │ │ │ │ │

I:84 keytable utilities │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

x11-xserver-utils V:34, 544 Utilitários do servido X: │ │ │ │ │

* I:51 xset(1), xmodmap(1) │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

daemon to manage events │ │ │ │ │

acpid * V:51, 208 delivered by the Advanced │ │ │ │ │

I:91 Configuration and Power │ │ │ │ │

Interface (ACPI) │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

V:4, utilitário para mostrar │ │ │ │ │

Page 548: Referências Debian

acpi * I:35 92 informação em dispositivos │ │ │ │ │

ACPI │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

V:1.2, daemon para gerir eventos │ │ │ │ │

apmd * I:11 252 entregues pelo Advanced │ │ │ │ │

Power Management (APM) │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

V:0.04, daemon que permite que │ │ │ │ │

noflushd * I:0.09 248 discos rijos inactivos parem│ │ │ │ │

o motor │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

daemon para colocar um │ │ │ │ │

sleepd * V:0.07, 148 portátil em modo de │ │ │ │ │

I:0.09 adormecimento durante a │ │ │ │ │

inactividade │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

hard disk access │ │ │ │ │

hdparm * V:11, 304 optimization (see │ │ │ │ │

I:38 Secção 9.3.7, “Optimização │ │ │ │ │

do disco rijo”) │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

smartmontools * V:7, 1076 control and monitor storage │ │ │ │ │

I:23 systems using S.M.A.R.T. │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

setserial * V:1.5, 180 colecção de ferramentas para│ │ │ │ │

Page 549: Referências Debian

I:3 gestão de portas série │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

V:0.5, colecção de ferramentas para│ │ │ │ │

memtest86+ * I:5 652 gestão de hardware de │ │ │ │ │

memória │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

scsitools * V:0.18, 484 collection of tools for SCSI│ │ │ │ │

I:1.1 hardware management │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

tpconfig * V:0.3, 220 utilitário para configurar │ │ │ │ │

I:0.5 dispositivos touchpad │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

setcd * V:0.06, 28 optimização de acesso a │ │ │ │ │

I:0.3 drives de discos compactos │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

big-cursor * I:0.16 68 cursores de rato maiores │ │ │ │ │

para o X │ │ │ │ │

└─────────────────┴───────┴───────┴────────────────────────────┘

Aqui, o ACPI é uma estrutura mais recente para o sistema de

gestão de energia que o APM.

Dica

Page 550: Referências Debian

O escalar de frequências da CPU em sistemas modernos é governado

por módulos do kernel como o acpi_cpufreq.

9.6.5. Hora do sistema e do hardware

O seguinte define a hora do sistema e hardware para MM/DD hh:mm,

AAAA.

# date MMDDhhmmAAAA

# hwclock --utc --systohc

# hwclock --show

Times are normally displayed in the local time on the Debian

system but the hardware and system time usually use UT(GMT).

If the hardware (BIOS) time is set to UT, change the setting to

"UTC=yes" in the "/etc/default/rcS".

If you wish to update system time via network, consider to use

the NTP service with the packages such as ntp, ntpdate, and

chrony.

Veja o seguinte.

Como Gerir a Data e Hora com Precisão●

NTP Public Services Project●

O pacote ntp-doc●

Dica

Page 551: Referências Debian

O ntptrace(8) no pacote ntp pode rastrear uma cadeia de

servidores NTP até à sua fonte principal.

9.6.6. A configuração do terminal

There are several components to configure character console and

ncurses(3) system features.

The "/etc/terminfo/*/*" file (terminfo(5))●

The "$TERM" environment variable (term(7))●

setterm(1), stty(1), tic(1), and toe(1)●

If the terminfo entry for xterm doesn't work with a non-Debian

xterm, change your terminal type, "$TERM", from "xterm" to one

of the feature-limited versions such as "xterm-r6" when you log

in to a Debian system remotely. See "/usr/share/doc/libncurses5/

FAQ" for more. "dumb" is the lowest common denominator for

"$TERM".

9.6.7. A infraestrutura de som

Device drivers for sound cards for current Linux 2.6 are

provided by Advanced Linux Sound Architecture (ALSA). ALSA

provides emulation mode for previous Open Sound System (OSS) for

compatibility.

Run "dpkg-reconfigure linux-sound-base" to select the sound

system to use ALSA via blacklisting of kernel modules. Unless

Page 552: Referências Debian

you have very new sound hardware, udev infrastructure should

configure your sound system.

Dica

Use "cat /dev/urandom > /dev/audio" or speaker-test(1) to test

speaker. (^C to stop)

Dica

If you can not get sound, your speaker may be connected to a

muted output. Modern sound system has many outputs. alsamixer(1)

in the alsa-utils package is useful to configure volume and mute

settings.

Application softwares may be configured not only to access sound

devices directly but also to access them via some standardized

sound server system.

Tabela 9.18. Lista de pacotes de som

┌──────────────────┬───────┬───────┬───────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

linux-sound-base * V:39, 132 pacote base para sistemas │ │ │ │ │

I:49 de som ALSA e OSS │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

Page 553: Referências Debian

alsa-base * V:2, 500 ficheiros de configuração │ │ │ │ │

I:48 da driver ALSA │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

alsa-utils * V:34, 1984 utilitários para configurar│ │ │ │ │

I:48 e utilizar ALSA │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

V:28, compatibilidade de OSS sob │ │ │ │ │

oss-compat * I:33 60 ALSA para prevenir erros de│ │ │ │ │

"/dev/dsp não encontrado" │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

V:19, Enlightened Sound Daemon │ │ │ │ │

esound-common * I:56 232 (ESD) comum (Enlightenment │ │ │ │ │

e GNOME) │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

V:0.6, Enlightened Sound Daemon │ │ │ │ │

esound * I:6 80 (ESD) servidor │ │ │ │ │

(Enlightenment e GNOME) │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

V:7, Enlightened Sound Daemon │ │ │ │ │

esound-clients * I:20 188 (ESD) cliente │ │ │ │ │

(Enlightenment e GNOME) │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

V:32, Enlightened Sound Daemon │ │ │ │ │

libesd0 * I:55 84 (ESD) biblioteca │ │ │ │ │

(Enlightenment e GNOME) │ │ │ │ │

Page 554: Referências Debian

├──────────────────┼───────┼───────┼───────────────────────────┤

arts * I:7 40 servidor aRts (KDE) │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

libarts1c2a * V:13, 5968 biblioteca aRts (KDE) │ │ │ │ │

I:23 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

libartsc0 * V:10, 48 biblioteca aRts (KDE) │ │ │ │ │

I:32 │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

V:0.8, JACK Audio Connection Kit. │ │ │ │ │

jackd * I:3 32 (JACK) servidor (baixa │ │ │ │ │

latência) │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

V:1.3, JACK Audio Connection Kit. │ │ │ │ │

libjack0 * I:33 164 (JACK) biblioteca (baixa │ │ │ │ │

latência) │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

nas * V:0.14, 328 Network Audio System (NAS) │ │ │ │ │

I:0.2 servidor │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

libaudio2 * V:26, 200 Network Audio System (NAS) │ │ │ │ │

I:46 biblioteca │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

pulseaudio * V:3, 4052 servidor PulseAudio, │ │ │ │ │

Page 555: Referências Debian

I:5 substituto para o ESD │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

V:15, biblioteca cliente │ │ │ │ │

libpulse0 * I:36 792 PulseAudio, substituto para│ │ │ │ │

o ESD │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

libgstreamer0.10-0 V:30, 3368 GStreamer: motor de som do │ │ │ │ │

* I:51 GNOME │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

libxine1 * V:5, 36 xine: antigo motor de som │ │ │ │ │

I:27 do KDE │ │ │ │ │

├──────────────────┼───────┼───────┼───────────────────────────┤

libphonon4 * I:16 572 Phonon: novo motor de som │ │ │ │ │

do KDE │ │ │ │ │

└──────────────────┴───────┴───────┴───────────────────────────┘

Existe normalmente um motor de som comum para cada ambiente de

trabalho popular. Cada motor de som usado pela aplicação pode

escolher ligar a diferentes servidores de som.

9.6.8. Desactivar o protector de écran (screensaver)

Para desactivar o protector de écran, use os seguintes comandos.

Tabela 9.19. Lista de comandos para desactivar o protector de

Page 556: Referências Debian

écran

┌─────────────────────────────────────────┬────────────────────┐

ambiente comando │ │ │

├─────────────────────────────────────────┼────────────────────┤

A consola do Linux setterm -powersave │ │ │

off │ │ │

├─────────────────────────────────────────┼────────────────────┤

O X Window (desactivar o protector de xset s off │ │ │

écran) │ │ │

├─────────────────────────────────────────┼────────────────────┤

O X Window (desactivar o dpms) xset -dpms │ │ │

├─────────────────────────────────────────┼────────────────────┤

O X Window (GUI de configuração do xscreensaver-command│ │ │

protector de écran) -prefs │ │ │

└─────────────────────────────────────────┴────────────────────┘

9.6.9. Desactivar os sons de beep

One can always unplug the PC speaker to disable beep sounds.

Removing pcspkr kernel module does this for you.

The following prevents the readline(3) program used by bash(1)

to beep when encountering "\a" (ASCII=7).

Page 557: Referências Debian

$ echo "set bell-style none">> ~/.inputrc

9.6.10. Utilização da memória

The kernel boot message in the "/var/log/dmesg" contains the

total exact size of available memory.

free(1) and top(1) display information on memory resources on

the running system.

$ grep '\] Memory' /var/log/dmesg

[ 0.004000] Memory: 990528k/1016784k available (1975k kernel code, 25868k reserved, 931k data, 296k init)

$ free -k

total used free shared buffers cached

Mem: 997184 976928 20256 0 129592 171932

-/+ buffers/cache: 675404 321780

Swap: 4545576 4 4545572

Dica

Do not worry about the large size of "used" and the small size

of "free" in the "Mem:" line, but read the one under them

(675404 and 321780 in the example below) and relax.

For my MacBook with 1GB=1048576k DRAM (video system steals some

of this), I see the following.

Page 558: Referências Debian

Tabela 9.20. Lista dos tamanhos de memória relatados

┌──────────────────────┬──────────────────────────────────┐

relato tamanho │ │ │

├──────────────────────┼──────────────────────────────────┤

Tamanho total no dmesg 1016784k = 1GB - 31792k │ │ │

├──────────────────────┼──────────────────────────────────┤

Livre no dmesg 990528k │ │ │

├──────────────────────┼──────────────────────────────────┤

Total sob a shell 997184k │ │ │

├──────────────────────┼──────────────────────────────────┤

Livre sob a shell 20256k (mas efectivamente 321780k)│ │ │

└──────────────────────┴──────────────────────────────────┘

9.6.11. Segurança do sistema e verificação de integridade

Uma manutenção pobre do sistema pode expor o seu sistema a

exploração externa.

Para segurança do sistema e verificação de integridade, você

deve começar com o seguinte.

O pacote debsums. Veja debsums(1) e Secção 2.5.2, “Ficheiro●

"Release" de nível de topo e autenticidade:”.

Page 559: Referências Debian

O pacote chkrootkit. Veja chkrootkit(1).●

A família de pacotes clamav. Veja clamscan(1) e freahclam●

(1).

FAQ de Segurança Debian.●

Manual de Segurança Debian.●

Tabela 9.21. Lista de ferramentas para segurança do sistema e

verificação de integridade

┌──────────┬───────┬───────┬───────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

V:3, daemon to mail anomalies in the │ │ │ │ │

logcheck * I:3 152 system logfiles to the │ │ │ │ │

administrator │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

V:2, utilitário para verifica pacotes │ │ │ │ │

debsums * I:3 320 instalados contra sumários de │ │ │ │ │

verificação MD5 │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

chkrootkit V:2, 808 detector de rootkit │ │ │ │ │

* I:6 │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

clamav * V:2, 616 anti-virus utility for Unix - │ │ │ │ │

I:11 command-line interface │ │ │ │ │

Page 560: Referências Debian

├──────────┼───────┼───────┼───────────────────────────────────┤

tiger * V:0.8, 3148 relatar vulnerabilidades de │ │ │ │ │

I:1.0 segurança do sistema │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

tripwire * V:0.6, 9456 verificador de integridade de │ │ │ │ │

I:0.7 ficheiros e directórios │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

john * V:0.7, 532 ferramenta de crack de │ │ │ │ │

I:2 palavras-passe activa │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

aide * V:0.2, 1213 Advanced Intrusion Detection │ │ │ │ │

I:0.4 Environment - static binary │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

bastille * V:0.12, 1960 security hardening tool │ │ │ │ │

I:0.4 │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

integrit * V:0.08, 440 programa de verificação de │ │ │ │ │

I:0.16 integridade de ficheiros │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

crack * V:0.03, 204 programa de adivinhação de │ │ │ │ │

I:0.2 palavra-passe │ │ │ │ │

└──────────┴───────┴───────┴───────────────────────────────────┘

Page 561: Referências Debian

Here is a simple script to check for typical world writable

incorrect file permissions.

# find / -perm 777 -a \! -type s -a \! -type l -a \! \( -type d -a -perm 1777 \)

Cuidado

Since the debsums package uses MD5 checksums stored locally, it

can not be fully trusted as the system security audit tool

against malicious attacks.

9.7. O kernel

Debian distributes modularized Linux kernel as packages for

supported architectures.

9.7.1. Kernel Linux 2.6

Existem algumas funcionalidades notáveis no kernel Linux 2.6

comparado ao 2.4.

Os dispositivos são criados pelo sistema udev (veja●

Secção 3.5.11, “O sistema udev”).

Read/write accesses to IDE CD/DVD devices do not use the●

ide-scsi module.

Network packet filtering functions use iptable kernel●

modules.

9.7.2. Parâmetros do kernel

Page 562: Referências Debian

Many Linux features are configurable via kernel parameters as

follows.

Kernel parameters initialized by the bootloader (see●

Secção 3.3, “Estágio 2: o gestor de arranque”)

Kernel parameters changed by syscrl(8) at runtime for ones●

accessible via sysfs (see Secção 1.2.12, “procfs e sysfs”)

Module parameters set by arguments of modprobe(8) when a●

module is activated (see Secção 10.2.3, “Montar o ficheiro

de imagem de disco”)

See "kernel-parameters.txt(.gz)" and other related documents in

the Linux kernel documentation ("/usr/share/doc/linux-doc-2.6.*/

Documentation/filesystems/*") provided by the linux-doc-2.6.*

package.

9.7.3. Cabeçalhos do kernel

Most normal programs don't need kernel headers and in fact may

break if you use them directly for compiling. They should be

compiled against the headers in "/usr/include/linux" and "/usr/

include/asm" provided by the libc6-dev package (created from the

glibc source package) on the Debian system.

Nota

For compiling some kernel-specific programs such as the kernel

modules from the external source and the automounter daemon

Page 563: Referências Debian

(amd), you must include path to the corresponding kernel

headers, e.g. "-I/usr/src/linux-particular-version/include/", to

your command line. module-assistant(8) (or its short form m-a)

helps users to build and install module package(s) easily for

one or more custom kernels.

9.7.4. Compilar o kernel e módulos relacionados

A Debian tem o seu método próprio de compilar o kernel e os

módulos relacionados.

Tabela 9.22. Lista de pacotes chave a serem instalados para a

recompilação do kernel no sistema Debian.

┌────────────────┬──────┬───────┬──────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├────────────────┼──────┼───────┼──────────────────────────────┤

build-essential pacotes essenciais para │ │ │ │ │

* I:47 48 construir pacotes Debian: │ │ │ │ │

make, gcc, … │ │ │ │ │

├────────────────┼──────┼───────┼──────────────────────────────┤

V:51, utilitários de compressão e │ │ │ │ │

bzip2 * I:79 132 descompressão para ficheiros │ │ │ │ │

bz2 │ │ │ │ │

├────────────────┼──────┼───────┼──────────────────────────────┤

libncurses5-dev V:4, 6900 bibliotecas de programadores e│ │ │ │ │

* I:25 documentos para ncurses │ │ │ │ │

Page 564: Referências Debian

├────────────────┼──────┼───────┼──────────────────────────────┤

V:5, git: distributed revision │ │ │ │ │

git * I:17 10632 control system used by the │ │ │ │ │

Linux kernel │ │ │ │ │

├────────────────┼──────┼───────┼──────────────────────────────┤

V:4, provide fakeroot environment │ │ │ │ │

fakeroot * I:32 444 for building package as │ │ │ │ │

non-root │ │ │ │ │

├────────────────┼──────┼───────┼──────────────────────────────┤

initramfs-tools V:49, ferramenta para construir uma │ │ │ │ │

* I:98 468 initramfs (específica de │ │ │ │ │

Debian) │ │ │ │ │

├────────────────┼──────┼───────┼──────────────────────────────┤

kernel-package * V:1.5, 2316 tool to build Linux kernel │ │ │ │ │

I:14 packages (Debian specific) │ │ │ │ │

├────────────────┼──────┼───────┼──────────────────────────────┤

module-assistant V:2, 568 tool to help build module │ │ │ │ │

* I:18 packages (Debian specific) │ │ │ │ │

├────────────────┼──────┼───────┼──────────────────────────────┤

dkms * V:6, 468 dynamic kernel module support │ │ │ │ │

I:9 (DKMS) (generic) │ │ │ │ │

├────────────────┼──────┼───────┼──────────────────────────────┤

V:2, helper scripts for a Debian │ │ │ │ │

devscripts * I:11 1696 Package maintainer (Debian │ │ │ │ │

specific) │ │ │ │ │

Page 565: Referências Debian

├────────────────┼──────┼───────┼──────────────────────────────┤

linux-tree-2.6.* N/D N/D Linux kernel source tree meta │ │ │ │ │

package (Debian specific) │ │ │ │ │

└────────────────┴──────┴───────┴──────────────────────────────┘

If you use initrd in Secção 3.3, “Estágio 2: o gestor de

arranque”, make sure to read the related information in

initramfs-tools(8), update-initramfs(8), mkinitramfs(8) and

initramfs.conf(5).

Atenção

Do not put symlinks to the directories in the source tree (e.g.

"/usr/src/linux*") from "/usr/include/linux" and "/usr/include/

asm" when compiling the Linux kernel source. (Some outdated

documents suggest this.)

Nota

When compiling the latest Linux kernel on the Debian stable

system, the use of backported latest tools from the Debian

unstable may be needed.

Nota

The dynamic kernel module support (DKMS) is a new distribution

independent framework designed to allow individual kernel

Page 566: Referências Debian

modules to be upgraded without changing the whole kernel. This

will be endorsed for the maintenance of out-of-tree modules for

squeeze. This also makes it very easy to rebuild modules as you

upgrade kernels.

9.7.5. Compilar a fonte do kernel: O método standard da Debian

The Debian standard method for compiling kernel source to create

a custom kernel package uses make-kpkg(1). The official

documentation is in (the bottom of) "/usr/share/doc/

kernel-package/README.gz". See kernel-pkg.conf(5) and

kernel-img.conf(5) for customization.

Aqui está um exemplo para sistema amd64.

# aptitude install linux-tree-<versão>

$ cd /usr/src

$ tar -xjvf linux-source-<versão>.tar.bz2

$ cd linux-source-<versão>

$ cp /boot/config-<versão-antiga> .config

$ make menuconfig

...

$ make-kpkg clean

$ fakeroot make-kpkg --append_to_version -amd64 --initrd --revision=rev.01 kernel_image modules_image

$ cd ..

# dpkg -i linux-image*.deb

Reiniciar para o novo kernel com "shutdown -r now".

Page 567: Referências Debian

Cuidado

When you intend to create a non-modularized kernel compiled only

for one machine, invoke make-kpkg without "--initrd" option

since initrd is not used. Invocation of "make oldconfig" and

"make dep" are not required since "make-kpkg kernel_image"

invokes them.

9.7.6. Compilar o módulo fontes: O método standard da Debian

The Debian standard method for creating and installing a custom

module package for a custom kernel package uses module-assistant

(8) and module-source packages. For example, the following

builds the unionfs kernel module package and installs it.

$ sudo aptitude install module-assistant

...

$ sudo aptitude install unionfs-source unionfs-tools unionfs-utils

$ sudo m-a update

$ sudo m-a prepare

$ sudo m-a auto-install unionfs

...

$ sudo apt-get autoremove

9.7.7. Compilar a fonte do kernel: O método clássico

You can still build Linux kernel from the pristine sources with

the classic method. You must take care the details of the system

Page 568: Referências Debian

configuration manually.

$ cd /usr/src

$ wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-<version>.tar.bz2

$ tar -xjvf linux-<version>.tar.bz2

$ cd linux-<version>

$ cp /boot/config-<version> .config

$ make menuconfig

...

$ make dep; make bzImage

$ make modules

# cp ./arch/x86_64/boot/bzImage /boot/vmlinuz-<version>

# make modules_install

# depmod -a

# update-initramfs -c -k <version>

Configurar o bootloader com o seguinte.

Edite o "/etc/lilo.conf" e corra "/sbin/lilo", se você usar●

o lilo.

Edite o "/boot/grub/menu.lst", se você usar o grub.●

Reiniciar para o novo kernel com "shutdown -r now".

9.7.8. Drivers de hardware não-livres

Although most of hardware drivers are available as free software

and as a part of the Debian system, you may need to load some

non-free external drivers to support some hardwares, such as

Page 569: Referências Debian

Winmodem, on your system.

Verificar recursos pertinentes.

http://en.wikipedia.org/wiki/Softmodem●

http://en.wikipedia.org/wiki/●

Comparison_of_open_source_wireless_drivers

Google ou outros motores de busca com a palavra "Linmodem".●

http://ndiswrapper.sourceforge.net●

http://linuxwireless.org●

http://madwifi-project.org (existe o ath5k que contém●

drivers livres)

9.8. Sistema virtualizado

Use of virtualized system enables us to run multiple instances

of system simultaneously on a single hardware.

Dica

Veja http://wiki.debian.org/SystemVirtualization .

9.8.1. Ferramentas de virtualização

There are several system virtualization and emulation related

packages in Debian beyond simple chroot. Some packages also help

you to setup such system.

Tabela 9.23. Lista de ferramentas de virtualização

Page 570: Referências Debian

┌───────────────┬───────┬───────┬──────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:1.0, ferramenta especializada para │ │ │ │ │

schroot * I:1.6 2460 executar pacotes binários │ │ │ │ │

Debian em chroot │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:0.11, ferramenta para construir │ │ │ │ │

sbuild * I:0.3 428 pacotes binários Debian a │ │ │ │ │

partir de fontes Debian │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

pbuilder * V:0.5, 1192 construtor de pacotes pessoais│ │ │ │ │

I:2 para pacotes Debian │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

debootstrap * V:1.6, 268 bootstrap a basic Debian │ │ │ │ │

I:12 system (written in sh) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

cdebootstrap * V:0.3, 116 bootstrap a Debian system │ │ │ │ │

I:2 (written in C) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:0.02, ferramenta para construir │ │ │ │ │

rootstrap * I:0.17 156 imagens de sistema de │ │ │ │ │

ficheiros de Linux completas │ │ │ │ │

Page 571: Referências Debian

├───────────────┼───────┼───────┼──────────────────────────────┤

Virtual Machine Manager: │ │ │ │ │

virt-manager * V:0.5, 5908 aplicação de ambiente de │ │ │ │ │

I:1.6 trabalho para gerir máquinas │ │ │ │ │

virtuais │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

libvirt-bin * V:1.4, 2240 programas para a biblioteca │ │ │ │ │

I:2 libvirt │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

user-mode-linux V:0.07, 20540 Modo-de-utilizador Linux │ │ │ │ │

* I:0.3 (kernel) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

bochs * V:0.05, 3280 Bochs: emulador PC IA-32 │ │ │ │ │

I:0.3 │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

qemu * V:0.6, 460 QEMU: emulador de processador │ │ │ │ │

I:6 genérico rápido │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

qemu-system * V:2, 38196 QEMU: binários de emulação de │ │ │ │ │

I:3 sistema completo │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

qemu-user * V:0.3, 16716 QEMU: binários de emulação em │ │ │ │ │

I:3 modo de utilizador │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

Page 572: Referências Debian

qemu-utils * V:0.4, 756 QEMU: utilitários │ │ │ │ │

I:3 │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

KVM: full virtualization on │ │ │ │ │

qemu-kvm * V:1.3, 4308 x86 hardware with the │ │ │ │ │

I:2 hardware-assisted │ │ │ │ │

virtualization │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

virtualbox-ose V:2, 31728 VirtualBox: x86 virtualization│ │ │ │ │

* I:4 solution on i386 and amd64 │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

xen-tools * V:0.2, 1236 ferramentas para gerir o │ │ │ │ │

I:1.9 servidor virtual XEN da debian│ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:1.7, Wine: Windows API │ │ │ │ │

wine * I:13 96 Implementation (standard │ │ │ │ │

suite) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:0.5, DOSBox: x86 emulator with │ │ │ │ │

dosbox * I:2 2460 Tandy/Herc/CGA/EGA/VGA/SVGA │ │ │ │ │

graphics, sound and DOS │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

dosemu * V:0.2, 5940 DOSEMU: O Emulador de DOS do │ │ │ │ │

I:1.2 Linux │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

Page 573: Referências Debian

vzctl * V:0.7, 1056 OpenVZ server virtualization │ │ │ │ │

I:1.1 solution - control tools │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

vzquota * V:0.7, 204 OpenVZ server virtualization │ │ │ │ │

I:1.2 solution - quota tools │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

lxc * V:0.05, 744 Linux containers user space │ │ │ │ │

I:0.2 tools │ │ │ │ │

└───────────────┴───────┴───────┴──────────────────────────────┘

See Wikipedia article Comparison of platform virtual machines

for detail comparison of different platform virtualization

solutions.

9.8.2. Fluxo de trabalho da virtualização

Nota

Some functionalities described here are only available in

squeeze.

Nota

Default Debian kernels support KVM since lenny.

Typical work flow for virtualization involves several steps.

Page 574: Referências Debian

Criar um sistema de ficheiros vazio (uma árvore de ficheiros●

ou uma imagem de disco).

A árvore de ficheiros pode ser criada por "mkdir -p /○

path/to/chroot".

The raw disk image file can be created with dd(1) (see○

Secção 10.2.1, “Criando o ficheiro de imagem de disco”

and Secção 10.2.5, “Criar um ficheiro de imagem de disco

vazio”).

qemu-img(1) pode ser usado para criar e converter○

ficheiros de imagem de disco suportados pelo QEMU.

The raw and VMDK file format can be used as common○

format among virtualization tools.

Montar a imagem de disco com mount(8) no sistema de●

ficheiros (opcional).

For the raw disk image file, mount it as loop device or○

device mapper devices (see Secção 10.2.3, “Montar o

ficheiro de imagem de disco”).

For disk images supported by QEMU, mount them as network○

block device (see Secção 9.8.3, “Montar o ficheiro de

imagem de disco virtual”).

Povoar o sistema de ficheiros alvo com os dados de sistema●

necessários.

Usar programas como o debootstrap e o cdebootstrap○

ajudam neste processo (veja Secção 9.8.4, “Sistema

chroot”).

Page 575: Referências Debian

Use instaladores de SOs sob o emulador de sistema○

completo.

Correr um programa sob um ambiente virtualizado●

chroot provides basic virtualized environment enough to○

compile programs, run console applications, and run

daemons in it.

QEMU oferece emulação de CPU de várias plataformas.○

QEMU com KVM oferece emulação de sistema completo pela○

virtualização assistida a hardware.

VirtualBox oferece emulação de sistema completo em i386○

ou amd64 com ou sem a virtualização assistida a hardware

.

9.8.3. Montar o ficheiro de imagem de disco virtual

Para o ficheiro de imagem de disco raw, veja Secção 10.2, “A

imagem de disco”.

Para outros ficheiros de imagem de disco virtual, você pode usar

o qemu-nbd para exportá-los usando o protocolo dispositivo de

bloco de rede e montá-los usando o módulo de kernel nbd.

qemu-nbd(8) supports disk formats supported by QEMU: QEMU

supports following disk formats: raw, qcow2, qcow, vmdk, vdi,

bochs, cow (user-mode Linux copy-on-write), parallels, dmg,

cloop, vpc, vvfat (virtual VFAT), and host_device.

The network block device can support partitions in the same way

Page 576: Referências Debian

as the loop device (see Secção 10.2.3, “Montar o ficheiro de

imagem de disco”). You can mount the first partition of

"disk.img" as follows.

# modprobe nbd max_part=16

# qemu-nbd -v -c /dev/nbd0 disk.img

...

# mkdir /mnt/part1

# mount /dev/nbd0p1 /mnt/part1

Dica

Você pode exportar apenas a primeira partição de "disk.img"

usando a opção "-P 1" para qemu-nbd(8).

9.8.4. Sistema chroot

chroot(8) oferece a maneira mais básica de correr diferentes

instâncias do ambiente GNU/Linux num único sistema em simultâneo

sem reiniciar.

Cuidado

Os exemplos em baixo assumem que ambos os sistemas pai e chroot

partilham a mesma arquitectura de CPU.

Você pode aprender a como configurar e usar chroot(8) ao correr

o programa pbuilder(8) sob script(1) como se segue.

Page 577: Referências Debian

$ sudo mkdir /sid-root

$ sudo pbuilder --create --no-targz --debug --buildplace /sid-root

Você vê como debootstrap(8) ou cdebootstrap(1) povoam dados do

sistema para ambiente sid sob "/sid-root".

Dica

Estes debootstrap(8) ou cdebootstrap(1) são usados para instalar

Debian pelo instalador Debian Installer. Estes também podem ser

usados para instalar Debian num sistema sem usar um disco de

instalação de Debian, mas em vez disso, a partir de outra

distribuição de GNU/Linux.

$ sudo pbuilder --login --no-targz --debug --buildplace /sid-root

Você pode ver como uma shell de sistema a correr sob ambiente

sid é criada como o seguinte.

1. Copiar configuração local ("/etc/hosts", "/etc/hostname", "/

etc/resolv.conf")

2. Montar o sistema de ficheiros "/proc"

3. Montar o sistema de ficheiros "/dev/pts"

4. Criar "/usr/sbin/policy-rc.d" o qual sempre existe com 101

5. Corra "chroot /sid-root bin/bash -c 'exec -a -bash bin/

bash'"

Nota

Page 578: Referências Debian

Some programs under chroot may require access to more files from

the parent system to function than pbuilder provides. For

example, "/sys", "/etc/passwd", "/etc/group", "/var/run/utmp", "

/var/log/wtmp", etc. may need to be bind-mounted or copied.

Nota

The "/usr/sbin/policy-rc.d" file prevents daemon programs to be

started automatically on Debian system. See "/usr/share/doc/

sysv-rc/README.policy-rc.d.gz".

Dica

The original purpose of the specialized chroot package, pbuilder

is to construct a chroot system and builds a package inside the

chroot. It is an ideal system to use to check that a package's

build-dependencies are correct, and to be sure that unnecessary

and wrong build dependencies do not exist in the resulting

package.

Dica

Similar schroot package may give you an idea to run i386 chroot

system under amd64 parent system.

9.8.5. Sistemas de múltiplos ambientes de trabalho

I recommend you to use QEMU or VirtualBox on a Debian stable

system to run multiple desktop systems safely using

Page 579: Referências Debian

virtualization. These enable you to run desktop applications of

Debian unstable and testing without usual risks associated with

them.

Since pure QEMU is very slow, it is recommended to accelerate it

with KVM when the host system support it.

The virtual disk image "virtdisk.qcow2" containing Debian system

for QEMU can be created using debian-installer: Small CDs as

follows.

$ wget http://cdimage.debian.org/debian-cd/5.0.3/amd64/iso-cd/debian-503-amd64-netinst.iso

$ qemu-img create -f qcow2 virtdisk.qcow2 5G

$ qemu -hda virtdisk.qcow2 -cdrom debian-503-amd64-netinst.iso -boot d -m 256

...

Veja mais dicas em Debian wiki: QEMU.

VirtualBox comes with Qt GUI tools and quite intuitive. Its GUI

and command line tools are explained in VirtualBox User Manual

and VirtualBox User Manual (PDF).

Dica

Running other GNU/Linux distributions such as Ubuntu and Fedra

under virtualization is a great way to learn configuration tips.

Other proprietary OSs may be run nicely under this GNU/Linux

virtualization, too.

Page 580: Referências Debian

Capítulo 10. Gestão de dados

São descritas ferramentas e dicas para gerir dados binários e de

texto no sistema Debian.

Atenção

The uncoordinated write access to actively accessed devices and

files from multiple processes must not be done to avoid the race

condition. File locking mechanisms using flock(1) may be used to

avoid it.

10.1. Partilhar, copiar e arquivar

A segurança dos dados e a sua partilha controlada têm vários

aspectos.

A criação de um arquivo de dados●

O acesso a armazenamento remoto●

A duplicação●

O acompanhar do histórico de modificação●

A facilitação da partilha de dados●

A prevenção de acessos não autorizados a ficheiros●

A detecção de modificação não autorizada de ficheiros●

Estas podem ser realizadas usando a combinação de algumas

ferramentas

Page 581: Referências Debian

Ferramentas de arquivo e compressão●

Ferramentas de cópia de sincronização●

Sistemas de ficheiros de rede●

Media de armazenamento amovível●

A shell segura●

O sistema de autenticação●

Ferramentas de sistema de controle de versão●

Ferramentas de hash e encriptação criptográfica●

10.1.1. Ferramentas de arquivo e compressão

Aqui está um sumário das ferramentas de arquivo e compressão

disponíveis no sistema Debian.

Tabela 10.1. Lista de ferramentas de arquivo e compressão

┌──────────┬──────┬───────┬───────┬────────┬───────────────────┐

pacote popcon tamanho comando extensão comentário │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

V:61, o arquivador │ │ │ │ │ │ │

tar * I:99 2660 tar(1) .tar standard (de facto │ │ │ │ │ │ │

standard) │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

V:41, arquivador estilo │ │ │ │ │ │ │

cpio * I:99 920 cpio(1) .cpio Unix System V, usar│ │ │ │ │ │ │

com o find(1) │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

Page 582: Referências Debian

arquivador para a │ │ │ │ │ │ │

binutils * V:58, 11996 ar(1) .ar criação de │ │ │ │ │ │ │

I:74 bibliotecas │ │ │ │ │ │ │

estáticas │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

fastjar * V:7, 216 fastjar .jar arquivador para │ │ │ │ │ │ │

I:31 (1) Java (estilo zip) │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

novo arquivador │ │ │ │ │ │ │

pax * V:1.5, 172 pax(1) .pax standard do POSIX, │ │ │ │ │ │ │

I:6 um compromisso │ │ │ │ │ │ │

entre tar e cpio │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

V:0.3, cpio extenso com │ │ │ │ │ │ │

afio * I:1.7 240 afio(1) .afio compressão por │ │ │ │ │ │ │

ficheiro etc. │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

gzip GNU LZ77 │ │ │ │ │ │ │

gzip * V:91, 284 (1), .gz compression utility│ │ │ │ │ │ │

I:99 zcat (de facto standard)│ │ │ │ │ │ │

(1), … │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

Burrows-Wheeler │ │ │ │ │ │ │

block-sorting │ │ │ │ │ │ │

bzip2 compression utility│ │ │ │ │ │ │

V:51, (1), with higher │ │ │ │ │ │ │

Page 583: Referências Debian

bzip2 * I:79 132 bzcat .bz2 compression ratio │ │ │ │ │ │ │

(1), … than gzip(1) │ │ │ │ │ │ │

(slower than gzip │ │ │ │ │ │ │

with similar │ │ │ │ │ │ │

syntax) │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

LZMA compression │ │ │ │ │ │ │

V:8, utility with higher│ │ │ │ │ │ │

lzma * I:80 172 lzma(1) .lzma compression ratio │ │ │ │ │ │ │

than gzip(1) │ │ │ │ │ │ │

(deprecated) │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

XZ compression │ │ │ │ │ │ │

utility with higher│ │ │ │ │ │ │

compression ratio │ │ │ │ │ │ │

xz(1), than bzip2(1) │ │ │ │ │ │ │

xz-utils * V:5, 460 xzdec .xz (slower than gzip │ │ │ │ │ │ │

I:26 (1), … but faster than │ │ │ │ │ │ │

bzip2; replacement │ │ │ │ │ │ │

for LZMA │ │ │ │ │ │ │

compression │ │ │ │ │ │ │

utility) │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

7zr(1), 7-Zip arquivador de│ │ │ │ │ │ │

p7zip * V:2, 1052 p7zip .7z ficheiros com alta │ │ │ │ │ │ │

I:23 (1) taxa de compressão │ │ │ │ │ │ │

(compressão LZMA) │ │ │ │ │ │ │

Page 584: Referências Debian

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

7-Zip file archiver│ │ │ │ │ │ │

p7zip-full V:14, 7z(1), with high │ │ │ │ │ │ │

* I:26 3612 7za(1) .7z compression ratio (│ │ │ │ │ │ │

LZMA compression │ │ │ │ │ │ │

and others) │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

LZO compression │ │ │ │ │ │ │

utility with higher│ │ │ │ │ │ │

compression and │ │ │ │ │ │ │

lzop * V:0.7, 144 lzop(1) .lzo decompression speed│ │ │ │ │ │ │

I:6 than gzip(1) (lower│ │ │ │ │ │ │

compression ratio │ │ │ │ │ │ │

than gzip with │ │ │ │ │ │ │

similar syntax) │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

V:8, InfoZIP: ferramenta│ │ │ │ │ │ │

zip * I:52 632 zip(1) .zip de compressão e │ │ │ │ │ │ │

arquivo do DOS │ │ │ │ │ │ │

├──────────┼──────┼───────┼───────┼────────┼───────────────────┤

InfoZIP: ferramenta│ │ │ │ │ │ │

unzip * V:24, 408 unzip .zip de descompressão e │ │ │ │ │ │ │

I:69 (1) de desarquivar do │ │ │ │ │ │ │

DOS │ │ │ │ │ │ │

└──────────┴──────┴───────┴───────┴────────┴───────────────────┘

Page 585: Referências Debian

Atenção

Não defina a variável "$TAPE" a menos que saiba com o que

esperar. Altera o comportamento do tar(1).

Nota

O arquivo tar(1) gzipado usa a extensão de ficheiro ".tgz" ou

".tar.gz".

Nota

O arquivo tar(1) comprimido em xz usa a extensão de ficheiro

".txz" ou ".tar.xz".

Nota

Popular compression method in FOSS tools such as tar(1) has been

moving as follows: gzip → bzip2 → xz

Nota

cp(1), scp(1) e tar(1) podem ter algumas limitações para

ficheiros especiais. cpio(1) e afio(1) são mais versáteis.

Nota

cpio(1) and afio(1) are designed to be used with find(1) and

Page 586: Referências Debian

other commands and suitable for creating backup scripts since

the file selection part of the script can be tested

independently.

Nota

afio(1) compresses each file in the archive. This makes afio to

be much safer for the file corruption than the globally

compressed tar or cpio archives and to be the best archive

engine for the backup script.

Nota

A estrutura interna dos ficheiros de dados do OpenOffice são

ficheiros ".jar".

10.1.2. Ferramentas de cópia de sincronização

Aqui está um sumário de ferramentas de cópia simples e

salvaguarda disponíveis no sistema Debian.

Tabela 10.2. Lista de ferramentas de cópia e sincronização

┌──────────────┬──────┬───────┬──────────┬─────────────────────┐

pacote popcon tamanho ferramenta função │ │ │ │ │ │

├──────────────┼──────┼───────┼──────────┼─────────────────────┤

copia localmente │ │ │ │ │ │

coreutils * V:92, 13828 GNU cp ficheiros e │ │ │ │ │ │

Page 587: Referências Debian

I:99 directórios ("-a" │ │ │ │ │ │

para ser recursivo) │ │ │ │ │ │

├──────────────┼──────┼───────┼──────────┼─────────────────────┤

copia remotamente │ │ │ │ │ │

openssh-client V:52, ficheiros e │ │ │ │ │ │

* I:99 2104 scp directórios (cliente,│ │ │ │ │ │

"-r" para ser │ │ │ │ │ │

recursivo) │ │ │ │ │ │

├──────────────┼──────┼───────┼──────────┼─────────────────────┤

copia ficheiros e │ │ │ │ │ │

openssh-server V:70, 700 sshd directórios │ │ │ │ │ │

* I:83 remotamente (servidor│ │ │ │ │ │

remoto) │ │ │ │ │ │

├──────────────┼──────┼───────┼──────────┼─────────────────────┤

V:19, sincronização remota │ │ │ │ │ │

rsync * I:52 704 - a salvaguarda de 1 │ │ │ │ │ │

via │ │ │ │ │ │

├──────────────┼──────┼───────┼──────────┼─────────────────────┤

V:0.9, sincronização remota │ │ │ │ │ │

unison * I:3 1816 - a salvaguarda de 2 │ │ │ │ │ │

vias │ │ │ │ │ │

└──────────────┴──────┴───────┴──────────┴─────────────────────┘

Copiar ficheiros com o rsync(8) oferece funcionalidades mais

ricas que os outros.

Page 588: Referências Debian

algoritmo de transferência delta que envia apenas as●

diferenças entre os ficheiros da fonte e os ficheiros

existentes no destino

algoritmo de verificação rápida (predefinido) que procura●

ficheiros que alteraram no tamanho ou ha hora da última

modificação

opções "--exclude" e "--exclude-from" semelhantes ao tar(1)●

"a trailing slash on the source directory" syntax that●

avoids creating an additional directory level at the

destination.

Dica

Execution of the bkup script mentioned in Secção 10.1.9, “Um

script de cópia para a salvaguarda de dados” with the "-gl"

option under cron(8) should provide very similar functionality

as Plan9's dumpfs for the static data archive.

Dica

Ferramentas de sistema de controlo de versão (VCS) em

Tabela 10.16, “lista de ferramentas de sistemas de controle de

versão” podem funcionar como a copia de multi-modos e

ferramentas de sincronização.

10.1.3. Idiomas para o arquivo

Aqui estão várias maneiras de arquivar e "desarquivar" o

Page 589: Referências Debian

conteúdo completo do directório "./source" usando diferentes

ferramentas.

GNU tar(1):

$ tar cvzf archive.tar.gz ./source

$ tar xvzf archive.tar.gz

cpio(1):

$ find ./source -xdev -print0 | cpio -ov --null > archive.cpio; gzip archive.cpio

$ zcat archive.cpio.gz | cpio -i

afio(1):

$ find ./source -xdev -print0 | afio -ovZ0 archive.afio

$ afio -ivZ archive.afio

10.1.4. Idiomas para a cópia

Aqui estão algumas maneiras de copiar o conteúdo inteiro do

directório "./source" usando diferentes ferramentas.

Cópia local: directório "./source" → directório "/dest"●

Cópia remota: directório "./source" em máquina local →●

directório "/dest" na máquina "utilizador@máquina.domínio"

rsync(8):

Page 590: Referências Debian

# cd ./source; rsync -av . /dest

# cd ./source; rsync -av . utilizador@máquina.domínio:/dest

You can alternatively use "a trailing slash on the source

directory" syntax.

# rsync -av ./source/ /dest

# rsync -av ./source/ utilizador@máquina.domínio:/dest

cp(1) de GNU e scp(1) de openSSH:

# cd ./source; cp -a . /dest

# cd ./source; scp -pr . utilizador@máquina.domínio:/dest

GNU tar(1):

# (cd ./source && tar cf - . ) | (cd /dest && tar xvfp - )

# (cd ./source && tar cf - . ) | ssh utilizador@máquina.domínio '(cd /dest && tar xvfp - )'

cpio(1):

# cd ./source; find . -print0 | cpio -pvdm --null --sparse /dest

afio(1):

# cd ./source; find . -print0 | afio -pv0a /dest

Você pode substituir "." por "foo" para todos os exemplos que

Page 591: Referências Debian

contêm "." para copiar ficheiros do directório "./source/foo"

para o directório "/dest/foo".

Você pode substituir "." pelo caminho absoluto "/caminho/para/

fonte/foo" para todos os exemplor que contém "." para abandonar

"cd ./source;". Estes copiam ficheiros para localizações

diferentes dependendo das ferramentas usadas como se segue.

"/dest/foo": rsync(8), cp(1) do GNU, e scp(1)●

"/dest/path/to/source/foo": tar(1) do GNU, cpio(1), e afio●

(1)

Dica

rsync(8) e cp(1) do GNU têm a opção "-u" para saltar ficheiros

que são mais recentes no receptor.

10.1.5. Idiomas para a selecção de ficheiros

find(1) is used to select files for archive and copy commands

(see Secção 10.1.3, “Idiomas para o arquivo” and Secção 10.1.4,

“Idiomas para a cópia”) or for xargs(1) (see Secção 9.5.9,

“Repeating a command looping over files”). This can be enhanced

by using its command arguments.

A sintaxe básica de find(1) pode ser sumariada no seguinte.

Os seus argumentos condicionais são avaliados da esquerda●

para a direita.

Page 592: Referências Debian

Esta avaliação pára assim que o seu resultado é determinado.●

O "OU lógico" (especificado por "-o" entre condicionais) tem●

precedência mais baixa que o "E lógico" (especificado por

"-a" ou nada entre condicionais).

O "NÃO lógico" (especificado por "!" antes duma condicional)●

tem precedência mas alta que o "E lógico".

"-prune" always returns logical TRUE and, if it is a●

directory, searching of file is stopped beyond this point.

"-name" matches the base of the filename with shell glob●

(see Secção 1.5.6, “Glob da shell”) but it also matches its

initial "." with metacharacters such as "*" and "?". (New

POSIX feature)

"-regex" corresponde ao caminho completo com estilo emacs●

BRE (veja Secção 1.6.2, “Expressões regulares”) como

predefinição.

"-size" corresponde ao ficheiro baseado no tamanho do●

ficheiro (valor precedido de "+" para maior, precedido de

"-" para menor)

"-newer" corresponde ao ficheiro mais recente que aquele●

especificado no seu argumento.

"-print0" retorna sempre o TRUE lógico e escreve o nome de●

ficheiro completo (terminado em nulo) na saída standard.

O find(1) é usado geralmente com um estilo idiomático como se

segue.

# procura /caminho/para \

-xdev -regextype posix-extended \

-type f -regex ".*\.afio|.*~" -prune -o \

Page 593: Referências Debian

-type d -regex ".*/\.git" -prune -o \

-type f -size +99M -prune -o \

-type f -newer /caminho/para/timestamp -print0

Isto significa fazer as seguintes acções.

1. Procura todos os ficheiros começando em "/caminho/para"

2. limita globalmente a sua busca dentro do sistema de

ficheiros inicial e usa ERE (veja antes Secção 1.6.2,

“Expressões regulares”)

3. Exclui da busca os ficheiros que correspondem à expressão

regular ".*\.afio" ou ".*~" ao parar o processamento

4. Exclui da busca os directórios que correspondem à expressão

regular ".*/\.git" ao parar o processamento

5. Exclui da busca os ficheiros maiores que 99 Mb (unidades de

1048576 bytes) ao parar o processamento

6. Escreve os nomes de ficheiros que satisfazem as condições de

busca em cima e são mais recentes que "/caminho/para/

timestamp"

Por favor note a utilização idiomática de "-prune -o" para

excluir ficheiros no exemplo em cima.

Nota

For non-Debian Unix-like system, some options may not be

supported by find(1). In such a case, please consider to adjust

matching methods and replace "-print0" with "-print". You may

need to adjust related commands too.

Page 594: Referências Debian

10.1.6. Salvaguarda (backup) e recuperação

Todos nós sabemos que os computadores avaria ou que erros

humanos causam danos no sistema e nos dados. As operações de

salvaguarda e recuperação são a parte essencial sucesso do

administrador de sistemas. Todos os modos de falha possíveis

irão atingi-lo um dia.

Dica

Mantenha o seu sistema de backup simples e faça backups

periódicos. Ter cópias de segurança dos dados é mais importante

do que quão bom é tecnicamente o seu método de backup.

Existem 3 factores chave que determinam a política actual de

salvaguarda e recuperação.

1. Saber o que salvaguardar e recuperar.

Ficheiros de dados criados directamente por si: dados em●

"~/"

Ficheiros de dados criados por aplicações usadas por si:●

dados em "/var/" (excepto "/var/cache/", "/var/run/", e

"/var/tmp/")

Ficheiros de configuração do sistema: dados em "/etc/"●

Softwares locais: dados em "/usr/local/" ou "/opt/"●

Informação da instalação do sistema: um memo em texto●

simples em passos chave (partição, ...)

Page 595: Referências Debian

Conjunto de dados de prova: confirmado com antecedência●

por operações de recuperação experimentais

2. Saber como salvaguardar e recuperar

Armazenamento de dados seguro: protecção contra●

re-escrita e falha do sistema

Salvaguarda frequente: salvaguarda agendada●

Backup redundante: usar mirror de dados●

Processo à prova de tolos: backup fácil de comando único●

3. Avaliar os riscos e custos envolvidos.

O valor dos dados quando perdidos●

Recursos necessários para o backup: humano, hardware,●

software, ...

Modo de falha e a sua possibilidade●

As for secure storage of data, data should be at least on

different disk partitions preferably on different disks and

machines to withstand the filesystem corruption. Important data

are best stored on a write-once media such as CD/DVD-R to

prevent overwrite accidents. (See Secção 10.3, “Os dados

binários” for how to write to the storage media from the shell

commandline. GNOME desktop GUI environment gives you easy access

via menu: "Places→CD/DVD Creator".)

Nota

Você pode desejar parar alguns daemons de aplicação como o MTA

(veja Secção 6.3, “Agente de transporte de mail (MTA)”) enquanto

Page 596: Referências Debian

faz cópias de segurança (backups) dos dados.

Nota

You should pay extra care to the backup and restoration of

identity related data files such as "/etc/ssh/ssh_host_dsa_key",

"/etc/ssh/ssh_host_rsa_key", "~/.gnupg/*", "~/.ssh/*", "/etc/

passwd", "/etc/shadow", "/etc/fetchmailrc",

"popularity-contest.conf", "/etc/ppp/pap-secrets", and "/etc/

exim4/passwd.client". Some of these data can not be regenerated

by entering the same input string to the system.

Nota

If you run a cron job as a user process, you must restore files

in "/var/spool/cron/crontabs" directory and restart cron(8). See

Secção 9.5.14, “Scheduling tasks regularly” for cron(8) and

crontab(1).

10.1.7. Suites de utilitários de salvaguardas (backup)

Aqui está uma lista seleccionada de suites de utilitários de

backup notáveis disponíveis no sistema Debian.

Tabela 10.3. Lista de suites utilitárias de salvaguarda

┌──────────────┬───────┬───────┬───────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

Page 597: Referências Debian

├──────────────┼───────┼───────┼───────────────────────────────┤

rdiff-backup * V:1.4, 804 salvaguarda incremental │ │ │ │ │

I:3 (remoto) │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

V:0.4, 4.4 BSD dump(8) e restore(8) │ │ │ │ │

dump * I:1.5 716 para sistemas de ficheiros ext2│ │ │ │ │

/ext3 │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

dump e restore com xfsdump(8) e│ │ │ │ │

xfsdump * V:0.3, 628 xfsrestore(8) para sistema de │ │ │ │ │

I:1.9 ficheiros XFS em GNU/Linux e │ │ │ │ │

IRIX │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

backupninja * V:0.5, 452 sistema de meta-backup leve e │ │ │ │ │

I:0.6 extensível │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

mondo * V:0.11, 1168 Mondo Rescue: suite de backup e│ │ │ │ │

I:0.5 recuperação de desastres │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

sbackup * V:0.05, 488 suite de salvaguarda simples │ │ │ │ │

I:0.16 para o ambiente GNOME │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

keep * V:0.13, 1232 sistema de salvaguarda para o │ │ │ │ │

I:0.3 KDE │ │ │ │ │

Page 598: Referências Debian

├──────────────┼───────┼───────┼───────────────────────────────┤

Bacula: salvaguarda, │ │ │ │ │

bacula-common V:1.3, 1404 recuperação e verificação em │ │ │ │ │

* I:2 rede - ficheiros de suporte │ │ │ │ │

comum │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

bacula-client Bacula: salvaguarda, │ │ │ │ │

* I:0.9 84 recuperação e verificação em │ │ │ │ │

rede - meta-pacote cliente │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

bacula-console V:0.3, Bacula: salvaguarda, │ │ │ │ │

* I:1.2 184 recuperação e verificação em │ │ │ │ │

rede - consola de texto │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

bacula-server Bacula: salvaguarda, │ │ │ │ │

* I:0.5 84 recuperação e verificação em │ │ │ │ │

rede - meta-pacote servidor │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

amanda-common V:0.4, Amanda: Advanced Maryland │ │ │ │ │

* I:0.8 6924 Automatic Network Disk Archiver│ │ │ │ │

(Bibliotecas) │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

amanda-client V:0.4, Amanda: Advanced Maryland │ │ │ │ │

* I:0.8 748 Automatic Network Disk Archiver│ │ │ │ │

(Cliente) │ │ │ │ │

Page 599: Referências Debian

├──────────────┼───────┼───────┼───────────────────────────────┤

amanda-server V:0.11, Amanda: Advanced Maryland │ │ │ │ │

* I:0.3 916 Automatic Network Disk Archiver│ │ │ │ │

(Servidor) │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

BackupPC é um sistema de grau │ │ │ │ │

backuppc * V:0.8, 2460 empresarial de alta performance│ │ │ │ │

I:1.0 para fazer salvaguardas a PCs │ │ │ │ │

(baseado em disco) │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

backup-manager V:0.4, 672 ferramenta de salvaguarda de │ │ │ │ │

* I:0.6 linha de comandos │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

ferramenta de baixa manutenção │ │ │ │ │

backup2l * V:0.2, 152 para salvaguarda/restauro para │ │ │ │ │

I:0.3 medias montáveis (baseado em │ │ │ │ │

disco) │ │ │ │ │

└──────────────┴───────┴───────┴───────────────────────────────┘

As ferramentas de salvaguarda têm os seus objectivos

especializados.

Mondo Rescue é um sistema de backup para facilitar o●

restauro de um sistema completo rapidamente a partir de CD/

DVD, etc de backup, sem se passar por todo o processo normal

Page 600: Referências Debian

de instalação do sistema.

sbackup and keep packages provide easy GUI frontend for●

desktop users to make regular backups of user data. An

equivalent function can be realized by a simple script (

Secção 10.1.8, “Um script de exemplo para salvaguarda ao

sistema”) and cron(8).

Bacula, Amanda, e BackupPC são suites utilitárias de●

salvaguarda cheias de funcionalidades que se destinam a

salvaguardas regulares em rede.

Ferramentas básicas descritas em Secção 10.1.1, “Ferramentas de

arquivo e compressão” e Secção 10.1.2, “Ferramentas de cópia de

sincronização” podem ser usadas facilitar o backup do sistema

via scripts personalizados. Tal script pode ser melhorado com o

seguinte.

O pacote rdiff-backup permite salvaguardas incrementais●

(remotas).

O pacote dump ajuda a arquivar e restaurar o sistema de●

ficheiros completo de modo incremental e eficiente.

Dica

Veja os ficheiros em "/usr/share/doc/dump/" e "está o dump mesmo

obsoleto?" para aprender acerca do oacote dump.

10.1.8. Um script de exemplo para salvaguarda ao sistema

For a personal Debian desktop system running unstable suite, I

Page 601: Referências Debian

only need to protect personal and critical data. I reinstall

system once a year anyway. Thus I see no reason to backup the

whole system or to install a full featured backup utility.

Eu uso um script simples para fazer um arquivo salvaguarda e

gravá-lo em CD/DVD usando uma GUI. Aqui está um script exemplo

para tal.

#!/bin/sh -e

# Copyright (C) 2007-2008 Osamu Aoki <[email protected]>, Public Domain

BUUID=1000; USER=osamu # UID and name of a user who accesses backup files

BUDIR="/var/backups"

XDIR0=".+/Mail|.+/Desktop"

XDIR1=".+/\.thumbnails|.+/\.?Trash|.+/\.?[cC]ache|.+/\.gvfs|.+/sessions"

XDIR2=".+/CVS|.+/\.git|.+/\.svn|.+/Downloads|.+/Archive|.+/Checkout|.+/tmp"

XSFX=".+\.iso|.+\.tgz|.+\.tar\.gz|.+\.tar\.bz2|.+\.afio|.+\.tmp|.+\.swp|.+~"

SIZE="+99M"

DATE=$(date --utc +"%Y%m%d-%H%M")

[ -d "$BUDIR" ] || mkdir -p "BUDIR"

umask 077

dpkg --get-selections \* > /var/lib/dpkg/dpkg-selections.list

debconf-get-selections > /var/cache/debconf/debconf-selections

{

find /etc /usr/local /opt /var/lib/dpkg/dpkg-selections.list \

/var/cache/debconf/debconf-selections -xdev -print0

find /home/$USER /root -xdev -regextype posix-extended \

-type d -regex "$XDIR0|$XDIR1" -prune -o -type f -regex "$XSFX" -prune -o \

-type f -size "$SIZE" -prune -o -print0

Page 602: Referências Debian

find /home/$USER/Mail/Inbox /home/$USER/Mail/Outbox -print0

find /home/$USER/Desktop -xdev -regextype posix-extended \

-type d -regex "$XDIR2" -prune -o -type f -regex "$XSFX" -prune -o \

-type f -size "$SIZE" -prune -o -print0

} | cpio -ov --null -O $BUDIR/BU$DATE.cpio

chown $BUUID $BUDIR/BU$DATE.cpio

touch $BUDIR/backup.stamp

Este é suposto ser um script de exemplo executado pelo root.

Eu espero que você altere e execute isto como o seguinte.

Edite este script para cobrir todos os seus dados●

importantes (veja Secção 10.1.5, “Idiomas para a selecção de

ficheiros” e Secção 10.1.6, “Salvaguarda (backup) e

recuperação”).

Substitua "find … -print0" por "find … -newer $BUDIR/●

backup.stamp -print0" para fazer uma salvaguarda

incremental.

Transfira os ficheiros de backup para a máquina remota●

usando scp(1) ou rsync(1) ou grave-os em CD/DVD para

segurança extra dos dados. (Eu uso a GUI do ambiente GNOME

para gravar CD/DVD. Veja See Secção 12.1.8, “Shell script

example with zenity” para redundância extra.)

Mantenha a coisa simples!

Dica

Page 603: Referências Debian

Você pode recuperar dados configuração debconf com

"debconf-set-selections debconf-selections" e dados de selecção

do dpkg com "dpkg --set-selection <dpkg-selections.list".

10.1.9. Um script de cópia para a salvaguarda de dados

Para o conjunto de dados sob uma árvore de directórios, a cópia

com "cp -a" disponibiliza um backup normal.

For the set of large non-overwritten static data under a

directory tree such as the one under the "/var/cache/apt/

packages/" directory, hardlinks with "cp -al" provide an

alternative to the normal backup with efficient use of the disk

space.

Aqui está um script de cópia, que Eu chamei de bkup, para o

backup de dados. O script copia todos os ficheiro (não-VCS) sob

o directório actual para o directório datado no directório pai

ou numa máquina remota.

#!/bin/sh -e

# Copyright (C) 2007-2008 Osamu Aoki <[email protected]>, Public Domain

fdot(){ find . -type d \( -iname ".?*" -o -iname "CVS" \) -prune -o -print0;}

fall(){ find . -print0;}

mkdircd(){ mkdir -p "$1";chmod 700 "$1";cd "$1">/dev/null;}

FIND="fdot";OPT="-a";MODE="CPIOP";HOST="localhost";EXTP="$(hostname -f)"

BKUP="$(basename $(pwd)).bkup";TIME="$(date +%Y%m%d-%H%M%S)";BU="$BKUP/$TIME"

while getopts gcCsStrlLaAxe:h:T f; do case $f in

Page 604: Referências Debian

g) MODE="GNUCP";; # cp (GNU)

c) MODE="CPIOP";; # cpio -p

C) MODE="CPIOI";; # cpio -i

s) MODE="CPIOSSH";; # cpio/ssh

S) MODE="AFIOSSH";; # afio/ssh

t) MODE="TARSSH";; # tar/ssh

r) MODE="RSYNCSSH";; # rsync/ssh

l) OPT="-alv";; # hardlink (GNU cp)

L) OPT="-av";; # copia (GNU cp)

a) FIND="fall";; # procura todos

A) FIND="fdot";; # procura não CVS/ .???/

x) set -x;; # trace

e) EXTP="${OPTARG}";; # hostname -f

h) HOST="${OPTARG}";; # [email protected]

T) MODE="TEST";; # teste ao modo de procura

\?) echo "use -x para trace."

esac; done

shift $(expr $OPTIND - 1)

if [ $# -gt 0 ]; then

for x in $@; do cp $OPT $x $x.$TIME; done

elif [ $MODE = GNUCP ]; then

mkdir -p "../$BU";chmod 700 "../$BU";cp $OPT . "../$BU/"

elif [ $MODE = CPIOP ]; then

mkdir -p "../$BU";chmod 700 "../$BU"

$FIND|cpio --null --sparse -pvd ../$BU

elif [ $MODE = CPIOI ]; then

$FIND|cpio -ov --null | ( mkdircd "../$BU"&&cpio -i )

elif [ $MODE = CPIOSSH ]; then

$FIND|cpio -ov --null|ssh -C $HOST "( mkdircd \"$EXTP/$BU\"&&cpio -i )"

Page 605: Referências Debian

elif [ $MODE = AFIOSSH ]; then

$FIND|afio -ov -0 -|ssh -C $HOST "( mkdircd \"$EXTP/$BU\"&&afio -i - )"

elif [ $MODE = TARSSH ]; then

(tar cvf - . )|ssh -C $HOST "( mkdircd \"$EXTP/$BU\"&& tar xvfp - )"

elif [ $MODE = RSYNCSSH ]; then

rsync -rlpt ./ "${HOST}:${EXTP}-${BKUP}-${TIME}"

else

echo "Mais alguma coisa para salvaguardar?"

$FIND |xargs -0 -n 1 echo

fi

Isto é suposto ser exemplos de comandos. Por favor, leia o

script e edite-o à sua necessidade antes de o usar.

Dica

Eu tenho este bkup no meu directório "/usr/local/bin/". Eu chamo

este comando bkup sem nenhuma opção no directório de trabalho

sempre que preciso duma imagem de backup temporária.

Dica

For making snapshot history of a source file tree or a

configuration file tree, it is easier and space efficient to use

git(7) (see Secção 10.9.5, “Git para gravar o histórico de

configuração”).

10.1.10. Dispositivo de armazenamento amovível

Page 606: Referências Debian

Dispositivos de armazenamento amovível podem ser qualquer um dos

seguintes.

Disco rijo●

Qualquer formato de dispositivos de memória flash●

Câmara Digital que está ligada via USB, IEEE 1394 / Firewire●

, PC Card, etc.

Estes dispositivos de armazenamento amovíveis pode ser montados

automaticamente como utilizador sob ambientes de trabalho

modernos, como o GNOME usando o gnome-mount(1).

O ponto de montagem sob GNOME é escolhido como "/media/●

<etiqueta_do_disco>" o que pode ser personalizado.

mlabel(1) para o sistema de ficheiros FAT○

genisoimage(1) com a opção "-V" para o sistema de○

ficheiros ISO9660

tune2fs(1) com a opção "-L" para sistemas de ficheiros○

ext2/ext3

A escolha de codificação pode necessitar de ser●

disponibilizada como opção de montagem (veja Secção 8.3.6,

“Codificação de nomes de ficheiros”).

O 'dono' do sistema de ficheiros montado pode necessitar de●

ser ajustado para utilização pelo utilizador normal.

Nota

A auto-montagem em ambientes de trabalho modernos apenas

Page 607: Referências Debian

acontece quando esses dispositivos amovíveis não estão listados

em "/etc/fstab".

Dica

Quando o fornecimento de opções de montagem erradas causar

problemas, apague as suas definições correspondentes sob "/

system/storage/" via gconf-editor(1).

Tabela 10.4. Lista de pacotes que permitem aos utilizadores

normais montarem dispositivos amovíveis sem uma entrada

correspondente no "/etc/fstab"

┌───────────┬──────┬─────────┬─────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├───────────┼──────┼─────────┼─────────────────────────────────┤

gnome-mount V:15, wrapper para (des)montar e │ │ │ │ │

* I:28 NOT_FOUND ejectar dispositivos de │ │ │ │ │

armazenamento (usado pelo GNOME) │ │ │ │ │

├───────────┼──────┼─────────┼─────────────────────────────────┤

V:4, montar dispositivos amovíveis │ │ │ │ │

pmount * I:19 548 como utilizador normal (usado │ │ │ │ │

pelo KDE) │ │ │ │ │

├───────────┼──────┼─────────┼─────────────────────────────────┤

cryptmount V:0.2, Gestão e montagem em modo de │ │ │ │ │

* I:0.5 360 utilizador de sistemas de │ │ │ │ │

ficheiros encriptados │ │ │ │ │

Page 608: Referências Debian

├───────────┼──────┼─────────┼─────────────────────────────────┤

V:0.4, montar e desmontar │ │ │ │ │

usbmount * I:1.4 112 automaticamente dispositivos de │ │ │ │ │

armazenamento USB │ │ │ │ │

└───────────┴──────┴─────────┴─────────────────────────────────┘

Quando partilha dados com outros sistemas via dispositivos de

armazenamento amovível, você deve formatá-lo num sistema de

ficheiros comum que seja suportado pelos dois sistemas. Aqui

está uma lista de escolhas de sistemas de ficheiros.

Tabela 10.5. Lista de hipóteses de sistemas de ficheiros para

dispositivos de armazenamento amovíveis com cenários de

utilização típica

┌──────────┬───────────────────────────────────────────────────┐

sistema de descrição do cenário de utilização típico │ │ │

ficheiros │ │ │

├──────────┼───────────────────────────────────────────────────┤

FAT12 partilha de dados em várias plataformas em │ │ │

disquetes (<32MiB) │ │ │

├──────────┼───────────────────────────────────────────────────┤

FAT16 partilha de dados em várias plataformas em │ │ │

dispositivos como pequenos discos rijos (<2GiB) │ │ │

Page 609: Referências Debian

├──────────┼───────────────────────────────────────────────────┤

partilha de dados em várias plataformas em │ │ │

FAT32 dispositivos como grandes discos rijos (<8TiB, │ │ │

suportado por mais recente que MS Windows95 OSR2) │ │ │

├──────────┼───────────────────────────────────────────────────┤

partilha de dados em várias plataformas em │ │ │

NTFS dispositivos como grandes discos rijos (suportado │ │ │

nativamente no MS Windows NT e versões posteriores,│ │ │

e suportado pelo NTFS-3G via FUSE em Linux) │ │ │

├──────────┼───────────────────────────────────────────────────┤

ISO9660 partilha de dados estáticos em várias plataformas │ │ │

em CD-R e DVD+/-R │ │ │

├──────────┼───────────────────────────────────────────────────┤

UDF escrita de dados incremental em CD-R e DVD+/-R │ │ │

(novo) │ │ │

├──────────┼───────────────────────────────────────────────────┤

sistema de armazenamento de dados em ficheiros unix eficiente │ │ │

ficheiros em espaço em disquetes │ │ │

MINIX │ │ │

├──────────┼───────────────────────────────────────────────────┤

sistema de partilha de dados em dispositivos tipo disco rijo │ │ │

ficheiros com sistemas Linux mais antigos │ │ │

ext2 │ │ │

├──────────┼───────────────────────────────────────────────────┤

sistema de partilha de dados em dispositivos tipo disco rijo │ │ │

Page 610: Referências Debian

ficheiros com sistemas Linux actuais (sistema de ficheiros │ │ │

ext3 com journal) │ │ │

└──────────┴───────────────────────────────────────────────────┘

Dica

Veja Secção 9.4.1, “Encriptação de discos amovíveis com dm-crypt

/LUKS” para partilha de dados em várias plataformas usando

encriptação ao nível do dispositivo.

O sistema de ficheiros FAT é suportado pela maioria dos sistemas

operativos modernos e é bastante útil para objectivos de trocas

de dados via dispositivos tipo disco rijo.

When formatting removable hard disk like devices for cross

platform sharing of data with the FAT filesystem, the following

should be safe choices.

Partitioning them with fdisk(8), cfdisk(8) or parted(8) (see●

Secção 9.3.1, “Configuração das partições do disco”) into a

single primary partition and to mark it as the following.

Tipo "6" para FAT16 para médias inferiores a 2GB○

Tipo "c" para FAT32 (LBA) para médias maiores○

Formatar a partição primária com o mkfs.vfat(8) com o●

seguinte.

Page 611: Referências Debian

Apenas o seu nome de dispositivo, ex. "/dev/sda1" para○

FAT16

A opção explícita e o seu nome de dispositivo, ex. "-F○

32 /dev/sda1" para FAT32

Quando se usa sistemas de ficheiros FAT ou ISO9660 para

partilhar dados, as considerações de segurança deverão ser as

seguintes.

Archiving files into an archive file first using tar(1),●

cpio(1), or afio(1) to retain the long filename, the

symbolic link, the original Unix file permission and the

owner information.

Splitting the archive file into less than 2 GiB chunks with●

the split(1) command to protect it from the file size

limitation.

Encriptar o ficheiro de arquivo para tornar seguro o seu●

conteúdo contra acesso não autorizado.

Nota

For FAT filesystems by its design, the maximum file size is (2^

32 - 1) bytes = (4GiB - 1 byte). For some applications on the

older 32 bit OS, the maximum file size was even smaller (2^31 -

1) bytes = (2GiB - 1 byte). Debian does not suffer the latter

problem.

Nota

Page 612: Referências Debian

Microsoft itself does not recommend to use FAT for drives or

partitions of over 200 MB. Microsoft highlights its short

comings such as inefficient disk space usage in their "Overview

of FAT, HPFS, and NTFS File Systems". Of course, we should

normally use the ext3 filesystem for Linux.

Dica

Para mais sistemas de ficheiros e acesso a sistemas de

ficheiros, por favor leia "HOWTO dos Sistemas de Ficheiros".

10.1.11. Partilhando dados via rede

Quando se partilha dados com outro sistema via rede, você deve

usar serviços comuns. Aqui estão algumas dicas.

Tabela 10.6. Lista de serviços de rede para escolher com o

cenário de utilização típico

┌─────────────────────┬────────────────────────────────────────┐

serviço de rede descrição do cenário de utilização │ │ │

típico │ │ │

├─────────────────────┼────────────────────────────────────────┤

SMB/CIFS sistema de sharing files via "Microsoft Windows │ │ │

ficheiros montado em Network", see smb.conf(5) and The │ │ │

rede com o Samba Official Samba 3.2.x HOWTO and Reference│ │ │

Guide or the samba-doc package │ │ │

Page 613: Referências Debian

├─────────────────────┼────────────────────────────────────────┤

NFS sistema de partilhar ficheiros via "Rede Unix/ │ │ │

ficheiros montado em Linux", veja exports(5) e Linux │ │ │

rede com o kernel do NFS-HOWTO │ │ │

Linux. │ │ │

├─────────────────────┼────────────────────────────────────────┤

serviço HTTP partilhando ficheiros entre o servidor/ │ │ │

cliente web │ │ │

├─────────────────────┼────────────────────────────────────────┤

sharing file between the web server/ │ │ │

serviço HTTPS client with encrypted Secure Sockets │ │ │

Layer (SSL) or Transport Layer Security │ │ │

(TLS) │ │ │

├─────────────────────┼────────────────────────────────────────┤

serviço FTP partilhando ficheiros entre o servidor/ │ │ │

cliente FTP │ │ │

└─────────────────────┴────────────────────────────────────────┘

Although these filesystems mounted over network and file

transfer methods over network are quite convenient for sharing

data, these may be insecure. Their network connection must be

secured by the following.

Encriptar com SSL/TLS●

Ligue-o em túnel via SSH●

Page 614: Referências Debian

Ligue-o em túnel via VPN●

Limitar por detrás da firewall segura●

Veja também Secção 6.10, “Outras aplicações de servidor de rede”

e Secção 6.11, “Outros clientes de aplicação de rede”.

10.1.12. Media de arquivo

When choosing computer data storage media for important data

archive, you should be careful about their limitations. For

small personal data backup, I use CD-R and DVD-R by the brand

name company and store in a cool, shaded, dry, clean

environment. (Tape archive media seem to be popular for

professional use.)

Nota

A fire-resistant safe are meant for paper documents. Most of the

computer data storage media have less temperature tolerance than

paper. I usually rely on multiple secure encrypted copies stored

in multiple secure locations.

Optimistic storage life of archive media seen on the net (mostly

from vendor info).

+ de 100 anos : Papel livre de ácidos com tinta●

100 anos : Armazenamento óptico (CD/DVD, CD/DVD-R)●

30 anos : Armazenamento magnético (fita, disquete)●

20 anos : Armazenamento óptico de mudança de fase (CD-RW)●

Page 615: Referências Debian

Estes não contam com falhas mecânicas devido a manuseamento e

etc.

Optimistic write cycle of archive media seen on the net (mostly

from vendor info).

+ de 250,000 ciclos : Disco rijo●

+ de 10,000 ciclos : Memória Flash●

1,000 ciclos : CD/DVD-RW●

1 ciclo : CD/DVD-R, papel●

Cuidado

Figures of storage life and write cycle here should not be used

for decisions on any critical data storage. Please consult the

specific product information provided by the manufacture.

Dica

Since CD/DVD-R and paper have only 1 write cycle, they

inherently prevent accidental data loss by overwriting. This is

advantage!

Dica

If you need fast and frequent backup of large amount of data, a

hard disk on a remote host linked by a fast network connection,

may be the only realistic option.

Page 616: Referências Debian

10.2. A imagem de disco

Aqui discutimos manipulações da imagem do disco. Veja também

Secção 9.3, “Dicas de armazenamento de dados”.

10.2.1. Criando o ficheiro de imagem de disco

O ficheiro de imagem de disco, "disco.img", de um dispositivo

não montado, ex., a segunda drive SCSI "/dev/sdb", pode ser

feito usando o cp(1) ou o dd(1) com o seguinte.

# cp /dev/sdb disco.img

# dd if=/dev/sdb of=disco.img

The disk image of the traditional PC's master boot record (MBR)

(see Secção 9.3.1, “Configuração das partições do disco”) which

reside on the first sector on the primary IDE disk can be made

by using dd(1) by the following.

# dd if=/dev/hda of=mbr.img bs=512 count=1

# dd if=/dev/hda of=mbr-nopart.img bs=446 count=1

# dd if=/dev/hda of=mbr-part.img skip=446 bs=1 count=66

"mbr.img": O MBR com a tabela de partições●

"mbr-nopart.img": O MBR sem a tabela de partições●

"part.img": A tabela de partições apenas do MBR●

If you have a SCSI device (including the new serial ATA drive)

Page 617: Referências Debian

as the boot disk, substitute "/dev/hda" with "/dev/sda".

Se você está a criar uma imagem de uma partição de disco do

disco original, substitua "/dev/hda" por "/dev/hda1" etc.

10.2.2. Escrever directamente no disco

O ficheiro de imagem de disco "disk.img" pode ser escrito para

um dispositivo desmontado, ex. a segunda drive SCSI "/dev/sdb"

como tamanho correspondente, com o seguinte.

# dd if=disk.img of=/dev/sdb

Similarly, the disk partition image file, "partition.img" can be

written to an unmounted partition, e.g., the first partition of

the second SCSI drive "/dev/sdb1" with matching size, by the

following.

# dd if=partition.img of=/dev/sdb1

10.2.3. Montar o ficheiro de imagem de disco

The disk image "partition.img" containing a single partition

image can be mounted and unmounted by using the loop device as

follows.

# losetup -v -f partition.img

Loop device is /dev/loop0

# mkdir -p /mnt/loop0

Page 618: Referências Debian

# mount -t auto /dev/loop0 /mnt/loop0

...hack...hack...hack

# umount /dev/loop0

# losetup -d /dev/loop0

Isto pode ser simplificado como se segue.

# mkdir -p /mnt/loop0

# mount -t auto -o loop partition.img /mnt/loop0

...hack...hack...hack

# umount partition.img

Each partition of the disk image "disk.img" containing multiple

partitions can be mounted by using the loop device. Since the

loop device does not manage partitions by default, we need to

reset it as follows.

# modinfo -p loop # verify kernel capability

max_part:Maximum number of partitions per loop device

max_loop:Maximum number of loop devices

# losetup -a # verify nothing using the loop device

# rmmod loop

# modprobe loop max_part=16

Agora, o dispositivo loop pode lidar com 16 partições (máximo).

# losetup -v -f disk.img

Loop device is /dev/loop0

# fdisk -l /dev/loop0

Page 619: Referências Debian

Disk /dev/loop0: 5368 MB, 5368709120 bytes

255 heads, 63 sectors/track, 652 cylinders

Units = cylinders of 16065 * 512 = 8225280 bytes

Disk identifier: 0x452b6464

Device Boot Start End Blocks Id System

/dev/loop0p1 1 600 4819468+ 83 Linux

/dev/loop0p2 601 652 417690 83 Linux

# mkdir -p /mnt/loop0p1

# mount -t ext3 /dev/loop0p1 /mnt/loop0p1

# mkdir -p /mnt/loop0p2

# mount -t ext3 /dev/loop0p2 /mnt/loop0p2

...hack...hack...hack

# umount /dev/loop0p1

# umount /dev/loop0p2

# losetup -d /dev/loop0

Alternatively, similar effects can be done by using the device

mapper devices created by kpartx(8) from the kpartx package as

follows.

# kpartx -a -v disk.img

...

# mkdir -p /mnt/loop0p2

# mount -t ext3 /dev/mapper/loop0p2 /mnt/loop0p2

...

...hack...hack...hack

# umount /dev/mapper/loop0p2

Page 620: Referências Debian

...

# kpartx -d /mnt/loop0

Nota

You can mount a single partition of such disk image with loop

device using offset to skip MBR etc., too. But this is more

error prone.

10.2.4. Limpar um ficheiro de imagem de disco

Um ficheiro de imagem de disco, "disk.img" pode ser limpo de

todos os ficheiros removidos em uma imagem limpa "new.img" com o

seguinte.

# mkdir old; mkdir new

# mount -t auto -o loop disk.img old

# dd bs=1 count=0 if=/dev/zero of=new.img seek=5G

# mount -t auto -o loop new.img new

# cd old

# cp -a --sparse=always ./ ../new/

# cd ..

# umount new.img

# umount disk.img

Se o "disk.img" está em ext2 ou ext3, você também pode usar o

zerofree(8) do pacote zerofree como se segue.

# losetup -f -v disk.img

Page 621: Referências Debian

Loop device is /dev/loop3

# zerofree /dev/loop3

# cp --sparse=always disco.img novo.img

10.2.5. Criar um ficheiro de imagem de disco vazio

A imagem de disco vazia "disk.img" que pode crescer até aos 5GiB

pode ser feita usando o dd(1) como se segue.

$ dd bs=1 count=0 if=/dev/zero of=disk.img seek=5G

Você pode criar um sistema de ficheiros ext3 nesta imagem de

disco "disk.img" usando o dispositivo loop como se segue.

# losetup -f -v disk.img

Loop device is /dev/loop1

# mkfs.ext3 /dev/loop1

...hack...hack...hack

# losetup -d /dev/loop1

$ du --apparent-size -h disk.img

5.0G disk.img

$ du -h disk.img

83M disk.img

For "disk.img", its file size is 5.0 GiB and its actual disk

usage is mere 83MiB. This discrepancy is possible since ext2fs

can hold sparse file.

Dica

Page 622: Referências Debian

The actual disk usage of sparse file grows with data which are

written to it.

Using similar operation on devices created by the loop device or

the device mapper devices as Secção 10.2.3, “Montar o ficheiro

de imagem de disco”, you can partition this disk image

"disk.img" using parted(8) or fdisk(8), and can create

filesystem on it using mkfs.ext3(8), mkswap(8), etc.

10.2.6. Criar o ficheiro de imagem ISO9660

The ISO9660 image file, "cd.iso", from the source directory tree

at "source_directory" can be made using genisoimage(1) provided

by cdrkit by the following.

# genisoimage -r -J -T -V volume_id -o cd.iso directório_fonte

Similarly, the bootable ISO9660 image file, "cdboot.iso", can be

made from debian-installer like directory tree at

"source_directory" by the following.

# genisoimage -r -o cdboot.iso -V volume_id \

-b isolinux/isolinux.bin -c isolinux/boot.cat \

-no-emul-boot -boot-load-size 4 -boot-info-table directório_fonte

Here Isolinux boot loader (see Secção 3.3, “Estágio 2: o gestor

de arranque”) is used for booting.

Page 623: Referências Debian

Você pode calcular o valor md5sum e fazer a imagem ISO9660

directamente a partir do dispositivo CD-ROM como se segue.

$ isoinfo -d -i /dev/cdrom

CD-ROM is in ISO 9660 format

...

Logical block size is: 2048

Volume size is: 23150592

...

# dd if=/dev/cdrom bs=2048 count=23150592 conv=notrunc,noerror | md5sum

# dd if=/dev/cdrom bs=2048 count=23150592 conv=notrunc,noerror > cd.iso

Atenção

You must carefully avoid ISO9660 filesystem read ahead bug of

Linux as above to get the right result.

10.2.7. Escrever directamente para o CD/DVD-R/RW

Dica

Um DVD é apenas um CD grande para o wodim(1) disponibilizado

pelo cdrkit.

Você pode procurar um dispositivo utilizável com o seguinte.

# wodim --devices

Então o CD-R vazio é inserido na drive de CD, e o ficheiro de

Page 624: Referências Debian

imagem ISO9660, "cd.iso" é escrito neste dispositivo, ex. "/dev/

hda", usando o wodim(1) com o seguinte.

# wodim -v -eject dev=/dev/hda cd.iso

Se for usado um CD-RW em vez de um CD-R, faça antes o seguinte.

# wodim -v -eject blank=fast dev=/dev/hda cd.iso

Dica

Se o seu ambiente montar CDs automaticamente, desmonte-o com

"sudo unmount /dev/hda" antes de usar o wodim(1).

10.2.8. Montar o ficheiro de imagem ISO9660

Se "cd.iso" conter uma imagem ISO9660, então o seguinte monta-o

manualmente em "/cdrom".

# mount -t iso9660 -o ro,loop cd.iso /cdrom

Dica

Modern desktop system mounts removable media automatically (see

Secção 10.1.10, “Dispositivo de armazenamento amovível”).

10.3. Os dados binários

Aqui, discutimos manipulação directa de dados binários em medias

Page 625: Referências Debian

de armazenamento. Veja também Secção 9.3, “Dicas de

armazenamento de dados”.

10.3.1. Ver e editar dados binários

The most basic viewing method of binary data is to use "od -t

x1" command.

Tabela 10.7. Lista de pacote para ver e editar dados binários

┌───────────────┬───────┬───────┬──────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:92, basic package which has od(1) │ │ │ │ │

coreutils * I:99 13828 to dump files (HEX, ASCII, │ │ │ │ │

OCTAL, …) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:81, utility package which has hd │ │ │ │ │

bsdmainutils * I:99 768 (1) to dump files (HEX, ASCII,│ │ │ │ │

OCTAL, …) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

hexedit * V:0.3, 108 editor binário e visualizador │ │ │ │ │

I:1.9 (HEX, ASCII) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

bless * V:0.08, 1232 editor hexadecimal cheiro de │ │ │ │ │

I:0.3 funcionalidades (GNOME) │ │ │ │ │

Page 626: Referências Debian

├───────────────┼───────┼───────┼──────────────────────────────┤

okteta * V:0.4, 2528 editor hexadecimal cheiro de │ │ │ │ │

I:3 funcionalidades (KDE4) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

ncurses-hexedit V:0.07, 192 editor binário e visualizador │ │ │ │ │

* I:0.5 (HEX, ASCII, EBCDIC) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

lde * V:0.04, 992 Editor de Disco de Linux │ │ │ │ │

I:0.3 │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

beav * V:0.03, 164 editor binário e visualizador │ │ │ │ │

I:0.3 (HEX, ASCII, EBCDIC, OCTAL, …)│ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:0.01, hexadecimal dumping tool │ │ │ │ │

hex * I:0.09 84 (support Japanese 2 byte │ │ │ │ │

codes) │ │ │ │ │

└───────────────┴───────┴───────┴──────────────────────────────┘

Dica

HEX is used as an acronym for hexadecimal format with radix 16.

OCTAL is for octal format with radix 8. ASCII is for American

Standard Code for Information Interchange, i.e., normal English

text code. EBCDIC is for Extended Binary Coded Decimal

Page 627: Referências Debian

Interchange Code used on IBM mainframe operating systems.

10.3.2. Manipular ficheiros sem montar o disco

Existem ferramentas para ler e escrever ficheiros sem montar o

disco.

Tabela 10.8. Lista de pacotes para ler e escrever ficheiros sem

montar o disco.

┌────────┬────────┬───────┬────────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├────────┼────────┼───────┼────────────────────────────────────┤

mtools * V:4, 408 utilitários para sistemas de │ │ │ │ │

I:42 ficheiros MSDOS sem os montar │ │ │ │ │

├────────┼────────┼───────┼────────────────────────────────────┤

hfsutils V:0.19, 236 utilitários para sistemas de │ │ │ │ │

* I:1.6 ficheiros HFS e HFS+ sem os montar │ │ │ │ │

└────────┴────────┴───────┴────────────────────────────────────┘

10.3.3. Redundância de dados

Software RAID systems offered by the Linux kernel provide data

redundancy in the kernel filesystem level to achieve high levels

of storage reliability.

Page 628: Referências Debian

There are tools to add data redundancy to files in application

program level to achieve high levels of storage reliability,

too.

Tabela 10.9. Lista de ferramentas para adicionar redundância de

dados a ficheiros

┌──────────┬───────┬───────┬───────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

par2 * V:0.5, 272 Parity Archive Volume Set, for │ │ │ │ │

I:1.7 checking and repair of files │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

dvdisaster V:0.14, protecção de dados contra percas/ │ │ │ │ │

* I:0.7 1388 riscos/envelhecimento para medias │ │ │ │ │

CD/DVD │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

V:0.01, ferramenta de backup que usa │ │ │ │ │

dvbackup * I:0.09 544 câmaras de filmar MiniDV │ │ │ │ │

(disponibilizando rsbep(1)) │ │ │ │ │

├──────────┼───────┼───────┼───────────────────────────────────┤

vdmfec * V:0.00, 88 recuperar blocos perdidos usando o │ │ │ │ │

I:0.02 Forward Error Correction │ │ │ │ │

└──────────┴───────┴───────┴───────────────────────────────────┘

Page 629: Referências Debian

10.3.4. Recuperação de ficheiros e dados e análise forense

Existem ferramentas para recuperação de ficheiros e dados e

análise forense.

Tabela 10.10. Lista de pacotes para recuperação de ficheiros e

dados e análise forense

┌─────────────┬───────┬───────┬────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.3, utilitários para sondagem de │ │ │ │ │

testdisk * I:3 4620 partições e recuperação de │ │ │ │ │

discos │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.07, utilitário para recuperar │ │ │ │ │

magicrescue * I:0.5 344 ficheiros ao procurar por bytes │ │ │ │ │

mágicos │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

scalpel * V:0.03, 124 frugal, entalhador de ficheiros │ │ │ │ │

I:0.2 de alta performance │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

myrescue * V:0.02, 84 recuperar dados de discos rijos │ │ │ │ │

I:0.18 danificados │ │ │ │ │

Page 630: Referências Debian

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.07, utilitários para recuperar │ │ │ │ │

recover * I:0.6 104 ficheiros apagados no sistema de│ │ │ │ │

ficheiros ext2 │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.07, utilitários para recuperar │ │ │ │ │

e2undel * I:0.5 244 ficheiros apagados no sistema de│ │ │ │ │

ficheiros ext2 │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.08, ferramenta para ajudar a │ │ │ │ │

ext3grep * I:0.6 300 recuperar ficheiros apagados no │ │ │ │ │

sistema de ficheiros ext3 │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

scrounge-ntfs V:0.03, 80 programa de recuperação de dados│ │ │ │ │

* I:0.4 para sistemas de ficheiros NTFS │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

gzrt * V:0.01, 68 conjunto de ferramentas de │ │ │ │ │

I:0.12 recuperação gzip │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

sleuthkit * V:0.13, 540 ferramentas para análise │ │ │ │ │

I:0.7 forense. (Sleuthkit) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

autopsy * V:0.07, 1372 interface gráfica para o │ │ │ │ │

I:0.4 SleuthKit │ │ │ │ │

Page 631: Referências Debian

├─────────────┼───────┼───────┼────────────────────────────────┤

foremost * V:0.11, 140 aplicação forense para recuperar│ │ │ │ │

I:0.8 dados │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

guymager * V:0.00, 688 ferramenta de imagem forense │ │ │ │ │

I:0.02 baseada em Qt │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

tct * V:0.03, 604 utilitários relacionados com │ │ │ │ │

I:0.2 forenses │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

dcfldd * V:0.03, 124 versão melhorada do dd para │ │ │ │ │

I:0.2 forenses e segurança │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

rdd * V:0.01, 200 programa de cópia forense │ │ │ │ │

I:0.11 │ │ │ │ │

└─────────────┴───────┴───────┴────────────────────────────────┘

10.3.5. Dividir um ficheiro grande em ficheiros pequenos

When a data is too big to backup as a single file, you can

backup its content after splitting it into, e.g. 2000MiB chunks

and merge those chunks back into the original file later.

$ split -b 2000m ficheiro_grande

Page 632: Referências Debian

$ cat x* >ficheiro_grande

Cuidado

Por favor certifique-se que não tem nenhuns ficheiros que

começam com "x" para evitar crashes com nomes.

10.3.6. Limpar conteúdo de ficheiro

In order to clear the contents of a file such as a log file, do

not use rm(1) to delete the file and then create a new empty

file, because the file may still be accessed in the interval

between commands. The following is the safe way to clear the

contents of the file.

$ :>ficheiro_a_ser_limpo

10.3.7. Ficheiros dummy

Os seguintes comandos criam ficheiros dummy ou vazios.

$ dd if=/dev/zero of=5kb.file bs=1k count=5

$ dd if=/dev/urandom of=7mb.file bs=1M count=7

$ touch zero.file

$ : > alwayszero.file

Você deve encontrar os seguintes ficheiros.

"5kb.file" é 5KB de zeros.●

Page 633: Referências Debian

"7mb.file" são 7MB de dados aleatórios.●

"zero.file" pode ser um ficheiro de 0 bytes. Se existir, o●

seu mtime é actualizado enquanto o seu conteúdo e tamanho

são mantidos.

"alwayszero.file" é sempre um ficheiro de 0 bytes. Se●

existir, o seu mtime é actualizado e o seu conteúdo é

reposto.

10.3.8. apagar um disco rijo inteiro

Existem várias maneiras de apagar completamente os dados de um

dispositivo inteiro tipo disco rijo, ex., stick de memória USB

em "/dev/sda".

Cuidado

Check your USB memory stick location with mount(8) first before

executing commands here. The device pointed by "/dev/sda" may be

SCSI hard disk or serial-ATA hard disk where your entire system

resides.

Apagar todo o conteúdo do disco ao repor os dados a 0 com o

seguinte.

# dd if=/dev/zero of=/dev/sda

Apagar tudo ao sobrescrever dados aleatórios com o seguinte.

# dd if=/dev/urandom of=/dev/sda

Page 634: Referências Debian

Apagar tudo ao sobrescrever dados aleatórios muito

eficientemente com o seguinte.

# shred -v -n 1 /dev/sda

Since dd(1) is available from the shell of many bootable Linux

CDs such as Debian installer CD, you can erase your installed

system completely by running an erase command from such media on

the system hard disk, e.g., "/dev/hda", "/dev/sda", etc.

10.3.9. Apagar uma área não utilizada do disco rijo

Unused area on an hard disk (or USB memory stick), e.g. "/dev/

sdb1" may still contain erased data themselves since they are

only unlinked from the filesystem. These can be cleaned by

overwriting them.

# mount -t auto /dev/sdb1 /mnt/foo

# cd /mnt/foo

# dd if=/dev/zero of=junk

dd: writing to `junk': No space left on device

...

# sync

# umount /dev/sdb1

Atenção

Normalmente isto é suficientemente bom para o seu stick de

Page 635: Referências Debian

memória USB. Mas não é perfeito. A maioria das partes dos nomes

de ficheiros apagados e os seus atributos podem ficar escondidos

e permanecerem no sistema de ficheiros.

10.3.10. Recuperar ficheiros apagados mas ainda abertos

Mesmo que tenha acidentalmente apagado um ficheiro, desde que

esse ficheiro esteja ainda a ser usado por alguma aplicação (em

modo de leitura ou escrita), é possível recuperar tal ficheiro.

Por exemplo, tente o seguinte

$ echo foo > bar

$ less bar

$ ps aux | grep ' less[ ]'

bozo 4775 0.0 0.0 92200 884 pts/8 S+ 00:18 0:00 less bar

$ rm bar

$ ls -l /proc/4775/fd | grep bar

lr-x------ 1 bozo bozo 64 2008-05-09 00:19 4 -> /home/bozo/bar (apagado)

$ cat /proc/4775/fd/4 >bar

$ ls -l

-rw-r--r-- 1 bozo bozo 4 2008-05-09 00:25 bar

$ cat bar

foo

Execute em outro terminal (quando tem o pacote lsof instalado) o

seguinte.

$ ls -li bar

Page 636: Referências Debian

2228329 -rw-r--r-- 1 bozo bozo 4 2008-05-11 11:02 bar

$ lsof |grep bar|grep less

less 4775 bozo 4r REG 8,3 4 2228329 /home/bozo/bar

$ rm bar

$ lsof |grep bar|grep less

less 4775 bozo 4r REG 8,3 4 2228329 /home/bozo/bar (apagado)

$ cat /proc/4775/fd/4 >bar

$ ls -li bar

2228302 -rw-r--r-- 1 bozo bozo 4 2008-05-11 11:05 bar

$ cat bar

foo

10.3.11. Procurar todos os hardlinks

Os ficheiros com hardlinks podem ser identificados com "ls -li".

$ ls -li

total 0

2738405 -rw-r--r-- 1 root root 0 2008-09-15 20:21 bar

2738404 -rw-r--r-- 2 root root 0 2008-09-15 20:21 baz

2738404 -rw-r--r-- 2 root root 0 2008-09-15 20:21 foo

Ambos "baz" e "foo" têm contagens de link de "2" (>1) mostrando

que têm hardlinks. Os números de inode deles são comuns

"2738404". Isto significa que eles são o mesmo ficheiro em

hardlink. Se você não encontrar todos os ficheiros em hardlink

por acaso, pode procurá-los pelo inode, ex., "2738404" com o

seguinte.

Page 637: Referências Debian

# find /caminho/para/ponto/de/montagem -xdev -inum 2738404

10.3.12. Consumo invisível do espaço do disco

Todos os ficheiros apagadas mas abertos consomem espaço no disco

apesar de não estarem visíveis ao du(1) normal. Eles podem ser

listados com o seu tamanho com o seguinte.

# lsof -s -X / |grep deleted

10.4. Infraestrutura da segurança de dados

The data security infrastructure is provided by the combination

of data encryption tool, message digest tool, and signature

tool.

Tabela 10.11. Lista de ferramentas de infraestrutura da

segurança de dados

┌──────────┬──────────────┬───────┬───────┬────────────────────┐

comando pacote popcon tamanho descrição │ │ │ │ │ │

├──────────┼──────────────┼───────┼───────┼────────────────────┤

GNU Privacy Guard - │ │ │ │ │ │

gpg(1) gnupg * V:43, 5288 ferramenta de │ │ │ │ │ │

I:99 encriptação e │ │ │ │ │ │

assinatura OpenPGP │ │ │ │ │ │

├──────────┼──────────────┼───────┼───────┼────────────────────┤

Page 638: Referências Debian

N/D gnupg-doc * I:1.1 4124 Documentação do GNU │ │ │ │ │ │

Privacy Guard │ │ │ │ │ │

├──────────┼──────────────┼───────┼───────┼────────────────────┤

GNU Privacy Guard - │ │ │ │ │ │

gpgv(1) gpgv * V:59, 436 ferramenta de │ │ │ │ │ │

I:99 verificação de │ │ │ │ │ │

assinaturas │ │ │ │ │ │

├──────────┼──────────────┼───────┼───────┼────────────────────┤

extrai apenas a │ │ │ │ │ │

paperkey paperkey * V:0.01, 88 informação secreta │ │ │ │ │ │

(1) I:0.10 de chaves secretas │ │ │ │ │ │

OpenPGP │ │ │ │ │ │

├──────────┼──────────────┼───────┼───────┼────────────────────┤

utilities for │ │ │ │ │ │

cryptsetup cryptsetup * V:3, 1172 dm-crypto block │ │ │ │ │ │

(8), … I:5 device encryption │ │ │ │ │ │

supporting LUKS │ │ │ │ │ │

├──────────┼──────────────┼───────┼───────┼────────────────────┤

utilities for │ │ │ │ │ │

ecryptfs ecryptfs-utils V:0.2, 416 ecryptfs stacked │ │ │ │ │ │

(7), … * I:0.3 filesystem │ │ │ │ │ │

encryption │ │ │ │ │ │

├──────────┼──────────────┼───────┼───────┼────────────────────┤

V:92, computa e verifica o│ │ │ │ │ │

md5sum(1) coreutils * I:99 13828 resumo da mensagem │ │ │ │ │ │

MD5 │ │ │ │ │ │

Page 639: Referências Debian

├──────────┼──────────────┼───────┼───────┼────────────────────┤

V:92, computa e verifica o│ │ │ │ │ │

sha1sum(1) coreutils * I:99 13828 resumo da mensagem │ │ │ │ │ │

SHA1 │ │ │ │ │ │

├──────────┼──────────────┼───────┼───────┼────────────────────┤

computa o resumo da │ │ │ │ │ │

openssl openssl * V:56, 2380 mensagem com │ │ │ │ │ │

(1ssl) I:91 "openssl dgst" │ │ │ │ │ │

(OpenSSL) │ │ │ │ │ │

└──────────┴──────────────┴───────┴───────┴────────────────────┘

See Secção 9.4, “Dicas de encriptação de dados” on dm-crypto and

ecryptfs which implement automatic data encryption

infrastructure via Linux kernel modules.

10.4.1. Gestão de chaves para GnuPG

Aqui estão comandos do GNU Privacy Guard para gestão de chaves

básica.

Tabela 10.12. Lista de comandos do GNU Privacy Guard para gestão

de chaves

┌────────────────────────┬─────────────────────────────────────┐

comando descrição │ │ │

Page 640: Referências Debian

├────────────────────────┼─────────────────────────────────────┤

gpg --gen-key gerar uma chave nova │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg --gen-revoke gera chave de revogação para │ │ │

meu_ID_utilizador meu_ID_utilizador │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg --edit-key edita chave interactivamente, "help" │ │ │

ID_utilizador para ajuda │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg -o ficheiro exporta todas as chaves para ficheiro│ │ │

--exports │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg --imports ficheiro importa todas as chaves de ficheiro │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg --send-keys envia chave de ID_utilizador para │ │ │

ID_utilizador servidor de chaves │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg --recv-keys recupera chave de ID_utilizador do │ │ │

ID_utilizador servidor de chaves │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg --list-keys lista chaves de ID_utilizador │ │ │

ID_utilizador │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg --list-sigs lista assinaturas de ID_utilizador │ │ │

Page 641: Referências Debian

ID_utilizador │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg --check-sigs verifica assinaturas de ID_utilizador│ │ │

ID_utilizador │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg --fingerprint verifica a impressão digital de │ │ │

ID_utilizador ID_utilizador │ │ │

├────────────────────────┼─────────────────────────────────────┤

gpg --refresh-keys actualiza o chaveiro local │ │ │

└────────────────────────┴─────────────────────────────────────┘

Aqui está o significado do código de confiança

Tabela 10.13. Lista do significado do código de confiança

┌──────┬───────────────────────────────────────────────────────┐

código descrição de confiança │ │ │

├──────┼───────────────────────────────────────────────────────┤

- nenhuma confiança de dono atribuída / ainda não │ │ │

calculado │ │ │

├──────┼───────────────────────────────────────────────────────┤

e falha no cálculo da confiança │ │ │

├──────┼───────────────────────────────────────────────────────┤

Page 642: Referências Debian

q não existe informação suficiente para o cálculo │ │ │

├──────┼───────────────────────────────────────────────────────┤

n nunca confiar nesta chave │ │ │

├──────┼───────────────────────────────────────────────────────┤

m marginalmente confiável │ │ │

├──────┼───────────────────────────────────────────────────────┤

f totalmente confiável │ │ │

├──────┼───────────────────────────────────────────────────────┤

u de confiança absoluta │ │ │

└──────┴───────────────────────────────────────────────────────┘

O seguinte envia a minha chave "1DD8D791" para o popular

servidor de chaves "hkp://keys.gnupg.net".

$ gpg --keyserver hkp://keys.gnupg.net --send-keys 1DD8D791

A good default keyserver set up in "~/.gnupg/gpg.conf" (or old

location "~/.gnupg/options") contains the following.

keyserver hkp://keys.gnupg.net

O seguinte obtém chaves desconhecidas do servidor de chaves.

$ gpg --list-sigs --with-colons | grep '^sig.*\[User ID not found\]' |\

cut -d ':' -f 5| sort | uniq | xargs gpg --recv-keys

Page 643: Referências Debian

There was a bug in OpenPGP Public Key Server (pre version 0.9.6)

which corrupted key with more than 2 sub-keys. The newer gnupg

(>1.2.1-2) package can handle these corrupted subkeys. See gpg

(1) under "--repair-pks-subkey-bug" option.

10.4.2. Usa GnuPG em ficheiros

Aqui estão exemplos para usar comandos do GNU Privacy Guard em

ficheiros.

Tabela 10.14. Lista de comandos do GNU Privacy Guard em

ficheiros

┌──────────────────────────┬───────────────────────────────────┐

comando descrição │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -a -s ficheiro sign file into ASCII armored │ │ │

file.asc │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg --armor --sign , , │ │ │

ficheiro │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg --clearsign ficheiro mensagem com assinatura clara │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg --clearsign file|mail envia por mail uma mensagem com │ │ │

Page 644: Referências Debian

[email protected] assinatura clara para │ │ │

[email protected] │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg --clearsign │ │ │

--not-dash-escaped ficheiro patch com assinatura clara│ │ │

patchfile │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg --verify ficheiro verifica ficheiro com assinatura │ │ │

clara │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -o ficheiro.sig -b cria assinatura separada │ │ │

ficheiro │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -o ficheiro.sig , , │ │ │

--detach-sig ficheiro │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg --verify ficheiro.sig verifica ficheiro com file.sig │ │ │

ficheiro │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -o crypt_file.gpg -r public-key encryption intended for │ │ │

nome -e ficheiro name from file to binary │ │ │

crypt_file.gpg │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -o crypt_file.gpg │ │ │

--recipient nome --encrypt , , │ │ │

Page 645: Referências Debian

ficheiro │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -o crypt_file.asc -a public-key encryption intended for │ │ │

-r nome -e ficheiro name from file to ASCII armored │ │ │

crypt_file.asc │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -o crypt_file.gpg -c symmetric encryption from file to │ │ │

ficheiro crypt_file.gpg │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -o crypt_file.gpg , , │ │ │

--symmetric ficheiro │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -o crypt_file.asc -a symmetric encryption intended for │ │ │

-c ficheiro name from file to ASCII armored │ │ │

crypt_file.asc │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -o ficheiro -d desencriptação │ │ │

crypt_file.gpg -r nome │ │ │

├──────────────────────────┼───────────────────────────────────┤

gpg -o ficheiro --decrypt , , │ │ │

crypt_file.gpg │ │ │

└──────────────────────────┴───────────────────────────────────┘

10.4.3. Usar GnuPG com o Mutt

Page 646: Referências Debian

Add the following to "~/.muttrc" to keep a slow GnuPG from

automatically starting, while allowing it to be used by typing

"S" at the index menu.

macro index S ":toggle pgp_verify_sig\n"

set pgp_verify_sig=no

10.4.4. Usar GnuPG com o Vim

The gnupg plugin let you run GnuPG transparently for files with

extension ".gpg", ".asc", and ".ppg".

# aptitude install vim-scripts vim-addon-manager

$ vim-addons install gnupg

10.4.5. O sumário MD5

md5sum(1) provides utility to make a digest file using the

method in rfc1321 and verifying each file with it.

$ md5sum foo bar >baz.md5

$ cat baz.md5

d3b07384d113edec49eaa6238ad5ff00 foo

c157a79031e1c40f85931829bc5fc552 bar

$ md5sum -c baz.md5

foo: OK

bar: OK

Page 647: Referências Debian

Nota

The computation for the MD5 sum is less CPU intensive than the

one for the cryptographic signature by GNU Privacy Guard (GnuPG)

. Usually, only the top level digest file is cryptographically

signed to ensure data integrity.

10.5. Ferramentas de fusão de código fonte

Existem muitas ferramentas de fusão para código fonte. Os

seguinte comandos chamaram a minha atenção.

Tabela 10.15. Lista de ferramentas de fusão de código fonte

┌───────────┬──────────┬───────┬───────┬───────────────────────┐

comando pacote popcon tamanho descrição │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

diff(1) diff * V:68, 36 compara ficheiros linha│ │ │ │ │ │

I:85 a linha │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

diff3(1) diff * V:68, 36 compara e funde três │ │ │ │ │ │

I:85 ficheiros linha a linha│ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

vimdiff(1) vim * V:15, 1792 compara dois ficheiros │ │ │ │ │ │

I:33 lado a lado no vim │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

Page 648: Referências Debian

patch(1) patch * V:10, 244 aplica ficheiro diff a │ │ │ │ │ │

I:92 um original │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

dpatch(1) dpatch * V:1.4, 344 gere séries de patches │ │ │ │ │ │

I:11 para pacote Debian │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

V:2, produz um histograma de│ │ │ │ │ │

diffstat(1) diffstat * I:15 92 alterações feitas pelo │ │ │ │ │ │

diff │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

combinediff patchutils V:1.8, cria uma patch │ │ │ │ │ │

(1) * I:14 292 cumulativa de duas │ │ │ │ │ │

patches incrementais │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

dehtmldiff patchutils V:1.8, 292 extrai um diff de uma │ │ │ │ │ │

(1) * I:14 página HTML │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

filterdiff patchutils V:1.8, 292 extrai ou executa diffs│ │ │ │ │ │

(1) * I:14 de um ficheiro diff │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

fixcvsdiff patchutils V:1.8, corrige ficheiros diff │ │ │ │ │ │

(1) * I:14 292 criados pelo CVS que o │ │ │ │ │ │

patch(1) interpreta mal│ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

flipdiff(1) patchutils V:1.8, 292 troca a ordem de duas │ │ │ │ │ │

Page 649: Referências Debian

* I:14 patches │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

mostra que ficheiros │ │ │ │ │ │

grepdiff(1) patchutils V:1.8, 292 são modificados por uma│ │ │ │ │ │

* I:14 patch que corresponde a│ │ │ │ │ │

um regex │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

interdiff patchutils V:1.8, mostra as diferenças │ │ │ │ │ │

(1) * I:14 292 entre dois ficheiros │ │ │ │ │ │

diff unificados │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

patchutils V:1.8, mostra quais ficheiros │ │ │ │ │ │

lsdiff(1) * I:14 292 são modificados por uma│ │ │ │ │ │

patch │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

recountdiff patchutils V:1.8, recompute counts and │ │ │ │ │ │

(1) * I:14 292 offsets in unified │ │ │ │ │ │

context diffs │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

rediff(1) patchutils V:1.8, 292 fix offsets and counts │ │ │ │ │ │

* I:14 of a hand-edited diff │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

splitdiff patchutils V:1.8, 292 separa patches │ │ │ │ │ │

(1) * I:14 incrementais │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

Page 650: Referências Debian

unwrapdiff patchutils V:1.8, 292 demangle patches that │ │ │ │ │ │

(1) * I:14 have been word-wrapped │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

wiggle(1) wiggle * V:0.01, 232 aplica patches │ │ │ │ │ │

I:0.11 rejeitadas │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

quilt(1) quilt * V:1.5, 872 gere séries de patches │ │ │ │ │ │

I:9 │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

meld(1) meld * V:0.7, 2576 compara e funde │ │ │ │ │ │

I:2 ficheiros (GTK) │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

xxdiff(1) xxdiff * V:0.2, 1352 compara e funde │ │ │ │ │ │

I:1.3 ficheiros (X simples) │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

V:0.08, mostra diferenças e │ │ │ │ │ │

dirdiff(1) dirdiff * I:0.6 224 funde alterações entre │ │ │ │ │ │

árvores de directórios │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

V:0.01, compara dois ficheiros │ │ │ │ │ │

docdiff(1) docdiff * I:0.14 688 palavra a palavra / │ │ │ │ │ │

caractere a caractere │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

V:0.02, ferramenta de fusão de │ │ │ │ │ │

imediff2(1) imediff2 * I:0.10 76 2 vias interactiva de │ │ │ │ │ │

Page 651: Referências Debian

écran completo │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

makepatch makepatch V:0.01, 148 gera ficheiros de patch│ │ │ │ │ │

(1) * I:0.17 extensos │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

applypatch makepatch V:0.01, 148 aplica ficheiros de │ │ │ │ │ │

(1) * I:0.17 patch extensos │ │ │ │ │ │

├───────────┼──────────┼───────┼───────┼───────────────────────┤

V:1.6, mostra diferenças de │ │ │ │ │ │

wdiff(1) wdiff * I:14 1024 palavras entre │ │ │ │ │ │

ficheiros de texto │ │ │ │ │ │

└───────────┴──────────┴───────┴───────┴───────────────────────┘

10.5.1. Extrair as diferenças para ficheiros fonte

One of following procedures extract differences between two

source files and create unified diff files "file.patch0" or

"file.patch1" depending on the file location.

$ diff -u ficheiro.antigo ficheiro.novo > ficheiro.patch0

$ diff -u antigo/ficheiro novo/ficheiro > ficheiro.patch1

10.5.2. Fundir actualizações para ficheiros de fonte

The diff file (alternatively called patch file) is used to send

a program update. The receiving party applies this update to

Page 652: Referências Debian

another file by the following.

$ patch -p0 ficheiro < ficheiro.patch0

$ patch -p1 ficheiro < ficheiro.patch1

10.5.3. Actualizar via fusão-de-3-vias

If you have three versions of a source code, you can perform

3-way-merge effectively using diff3(1) by the following.

$ diff3 -m meu.ficheiro ficheiro.antigo teu.ficheiro > ficheiro

10.6. Sistemas de controle de versão

Aqui está um sumário dos sistemas de controle de versão (VCS) no

sistema Debian.

Nota

Se você é novato nos sistemas VCS, deverá começar a aprender com

o Git, o qual está a crescer rapidamente na popularidade.

Tabela 10.16. lista de ferramentas de sistemas de controle de

versão

┌──────────┬───────┬───────┬──────────┬───────────┬───────────────┐

pacote popcon tamanho ferramenta Tipo VCS comentário │ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

Page 653: Referências Debian

V:0.00, clone do SCCS │ │ │ │ │ │ │

cssc * I:0.04 2240 CSSC local do Unix │ │ │ │ │ │ │

(descontinuado)│ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

rcs * V:1.3, 772 RCS local "SCCS do Unix │ │ │ │ │ │ │

I:7 bem feito" │ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

V:3, VCS remoto │ │ │ │ │ │ │

cvs * I:21 3660 CVS remoto standard │ │ │ │ │ │ │

anterior │ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

"CVS bem │ │ │ │ │ │ │

subversion V:10, feito", o novo │ │ │ │ │ │ │

* I:31 4288 Subversion remoto VCS remoto │ │ │ │ │ │ │

standard "de │ │ │ │ │ │ │

facto" │ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

DVCS rápido em │ │ │ │ │ │ │

git * V:5, 10632 Git distribuído C (usado pelo │ │ │ │ │ │ │

I:17 kernel Linux e │ │ │ │ │ │ │

outros) │ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

mercurial V:1.8, 368 Mercurial distribuído DVCS em Python │ │ │ │ │ │ │

* I:6 e algum C │ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

Page 654: Referências Debian

DVCS │ │ │ │ │ │ │

influenciado │ │ │ │ │ │ │

bzr * V:1.1, 16220 Bazaar distribuído por tla escrito│ │ │ │ │ │ │

I:3 em Python │ │ │ │ │ │ │

(usado pelo │ │ │ │ │ │ │

Ubuntu) │ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

DVCS com │ │ │ │ │ │ │

darcs * V:0.19, 9504 Darcs distribuído algebra │ │ │ │ │ │ │

I:1.4 inteligente de │ │ │ │ │ │ │

patches (lento)│ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

DVCS │ │ │ │ │ │ │

tla * V:0.17, 932 GNU arch distribuído principalmente │ │ │ │ │ │ │

I:1.4 por Tom Lord │ │ │ │ │ │ │

(Histórico) │ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

monotone * V:0.04, 5272 Monotone distribuído DVCS em C++ │ │ │ │ │ │ │

I:0.3 │ │ │ │ │ │ │

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

Mostrador GUI │ │ │ │ │ │ │

de árvores de │ │ │ │ │ │ │

tkcvs * V:0.08, 2476 CVS, … remoto repositório VCS│ │ │ │ │ │ │

I:0.4 (CVS, │ │ │ │ │ │ │

Subversion, │ │ │ │ │ │ │

RCS) │ │ │ │ │ │ │

Page 655: Referências Debian

├──────────┼───────┼───────┼──────────┼───────────┼───────────────┤

Mostrador GUI │ │ │ │ │ │ │

gitk * V:0.8, 900 Git distribuído de árvores de │ │ │ │ │ │ │

I:4 repositório VCS│ │ │ │ │ │ │

(Git) │ │ │ │ │ │ │

└──────────┴───────┴───────┴──────────┴───────────┴───────────────┘

VCS is sometimes known as revision control system (RCS), or

software configuration management (SCM).

Distributed VCS such as Git is the tool of choice these days.

CVS and Subversion may still be useful to join some existing

open source program activities.

Debian provides free VCS services via Debian Alioth service. It

supports practically all VCSs. Its documentation can be found at

http://wiki.debian.org/Alioth .

Cuidado

O pacote git era "GNU Interactive Tools" e o pacote git-core era

DVCS em lenny.

There are few basics for creating a shared access VCS archive.

Use "umask 002" (see Secção 1.2.4, “Control de permissões●

para ficheiros acabados de criar: umask”)

Page 656: Referências Debian

Make all VCS archive files belonging to a pertinent group●

Enable set group ID on all VCS archive directories (BSD-like●

file creation scheme, see Secção 1.2.3, “Permissões do

sistema de ficheiros”)

Make user sharing the VCS archive belonging to the group●

10.6.1. Comparação dos comandos VCS

Here is an oversimplified comparison of native VCS commands to

provide the big picture. The typical command sequence may

require options and arguments.

Tabela 10.17. Comparação dos comandos VCS nativos

┌──────┬──────────┬──────────────┬─────────────────────────────┐

CVS Subversion Git função │ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

cvs svn create git init cria o repositório (local) │ │ │ │ │

init │ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

cvs - - login ao repositório remoto │ │ │ │ │

login │ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

check out the remote │ │ │ │ │

cvs co svn co git clone repository as the working │ │ │ │ │

tree │ │ │ │ │

Page 657: Referências Debian

├──────┼──────────┼──────────────┼─────────────────────────────┤

cvs up svn up git pull update the working tree by │ │ │ │ │

merging the remote repository│ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

cvs svn add git add . adiciona ficheiro(s) na │ │ │ │ │

add árvore de trabalho do VCS │ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

cvs rm svn rm git rm remove ficheiro(s) na árvore │ │ │ │ │

de trabalho do VCS │ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

cvs ci svn ci - comete alterações para o │ │ │ │ │

repositório remoto │ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

- - git commit -a comete alterações para o │ │ │ │ │

repositório local │ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

- - git push actualiza o repositório │ │ │ │ │

remoto pelo repositório local│ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

cvs svn status git status mostra o estado da árvore de │ │ │ │ │

status trabalho do VCS │ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

cvs svn diff git diff diff <reference_repository> │ │ │ │ │

diff <working_tree> │ │ │ │ │

Page 658: Referências Debian

├──────┼──────────┼──────────────┼─────────────────────────────┤

- - git repack -a re-empacota o repositório │ │ │ │ │

-d; git prune local em um único pacote │ │ │ │ │

├──────┼──────────┼──────────────┼─────────────────────────────┤

tkcvs tkcvs gitk Mostrador GUI de árvore de │ │ │ │ │

repositório VCS │ │ │ │ │

└──────┴──────────┴──────────────┴─────────────────────────────┘

Cuidado

Invoking a git subcommand directly as "git-xyz" from the command

line has been deprecated since early 2006.

Dica

GUI tools such as tkcvs(1) and gitk(1) really help you with

tracking revision history of files. The web interface provided

by many public archives for browsing their repositories is also

quite useful, too.

Dica

Git can work directly with different VCS repositories such as

ones provided by CVS and Subversion, and provides the local

repository for local changes with git-cvs and git-svn packages.

See git for CVS users, and Secção 10.9.4, “Git para o

Page 659: Referências Debian

repositório Subversion”.

Dica

Git has commands which have no equivalents in CVS and

Subversion: "fetch", "rebase", "cherry-pick", …

10.7. CVS

Veja o seguinte.

cvs(1)●

"/usr/share/doc/cvs/html-cvsclient"●

"/usr/share/doc/cvs/html-info"●

"/usr/share/doc/cvsbook"●

"info cvs"●

10.7.1. Configuração de repositório CVS

The following configuration allows commits to the CVS repository

only by a member of the "src" group, and administration of CVS

only by a member of the "staff" group, thus reducing the chance

of shooting oneself.

# cd /var/lib; umask 002; mkdir cvs

# export CVSROOT=/srv/cvs/project

# cd $CVSROOT

# chown root:src .

# chmod 2775 .

Page 660: Referências Debian

# cvs -d $CVSROOT init

# cd CVSROOT

# chown -R root:staff .

# chmod 2775 .

# touch val-tags

# chmod 664 history val-tags

# chown root:src history val-tags

Dica

You may restrict creation of new project by changing the owner

of "$CVSROOT" directory to "root:staff" and its permission to

"3775".

10.7.2. Acesso local ao CVS

The default CVS repository is pointed by "$CVSROOT". The

following sets up "$CVSROOT" for the local access.

$ export CVSROOT=/srv/cvs/project

10.7.3. Acesso remoto ao CVS com pserver

Many public CVS servers provide read-only remote access to them

with account name "anonymous" via pserver service. For example,

Debian web site contents are maintained by webwml project via

CVS at Debian alioth service. The following sets up "$CVSROOT"

for the remote access to this CVS repository.

Page 661: Referências Debian

$ export CVSROOT=:pserver:[email protected]:/cvsroot/webwml

$ cvs login

Nota

Since pserver is prone to eavesdropping attack and insecure,

write access is usually disable by server administrators.

10.7.4. Acesso remoto ao CVS com ssh

The following sets up "$CVS_RSH" and "$CVSROOT" for the remote

access to the CVS repository by webwml project with SSH.

$ export CVS_RSH=ssh

$ export CVSROOT=:ext:[email protected]:/cvs/webwml

Você também pode usar autenticação de chave pública para SSH o

que elimina o pedido remoto de palavra-passe.

10.7.5. Importar uma nova fonte para o CVS

Crie uma nova localização de árvore fonte local em "~/caminho/

para/module1" com o seguinte.

$ mkdir -p ~/caminho/para/module1; cd ~/caminho/para/module1

Populate a new local source tree under "~/path/to/module1" with

files.

Page 662: Referências Debian

Importe-o para o CVS com os seguintes parâmetros.

Module name: "module1"●

Vendor tag: "Main-branch" (etiqueta para o branch completo)●

Release tag: "Release-initial" (etiqueta para um lançamento●

específico)

$ cd ~/caminho/para/module1

$ cvs import -m "Start module1" module1 Main-branch Release-initial

$ rm -Rf . # opcional

10.7.6. Permissões de ficheiros no repositório CVS

CVS does not overwrite the current repository file but replaces

it with another one. Thus, write permission to the repository

directory is critical. For every new module for "module1" in

repository at "/srv/cvs/project", run the following to ensure

this condition if needed.

# cd /srv/cvs/project

# chown -R root:src module1

# chmod -R ug+rwX module1

# chmod 2775 module1

10.7.7. Fluxo de trabalho do CVS

Aqui está um exemplo de um fluxo de trabalho típico usando CVS

Page 663: Referências Debian

Check all available modules from CVS project pointed by

"$CVSROOT" by the following.

$ cvs rls

CVSROOT

module1

module2

...

Checkout "module1" to its default directory "./module1" by the

following.

$ cd ~/caminho/para

$ cvs co module1

$ cd module1

Faça as alterações necessárias ao conteúdo.

Check changes by making "diff -u [repository] [local]"

equivalent by the following.

$ cvs diff -u

You find that you broke some file "file_to_undo" severely but

other files are fine.

Overwrite "file_to_undo" file with the clean copy from CVS by

the following.

Page 664: Referências Debian

$ cvs up -C file_to_undo

Save the updated local source tree to CVS by the following.

$ cvs ci -m "Describe change"

Create and add "file_to_add" file to CVS by the following.

$ vi file_to_add

$ cvs add file_to_add

$ cvs ci -m "Added file_to_add"

Merge the latest version from CVS by the following.

$ cvs up -d

Watch out for lines starting with "C filename" which indicates

conflicting changes.

Look for unmodified code in ".#filename.version".

Search for "<<<<<<<" and ">>>>>>>" in files for conflicting

changes.

Edit files to fix conflicts as needed.

Adicione uma etiqueta de lançamento "Release-1" com o seguinte.

$ cvs ci -m "last commit for Release-1"

Page 665: Referências Debian

$ cvs tag Release-1

Continuar a editar.

Remova a etiqueta de lançamento "Release-1" com o seguinte.

$ cvs tag -d Release-1

Verifique as alterações no CVS com o seguinte.

$ cvs ci -m "real last commit for Release-1"

Re-add the release tag "Release-1" to updated CVS HEAD of main

by the following.

$ cvs tag Release-1

Create a branch with a sticky branch tag

"Release-initial-bugfixes" from the original version pointed by

the tag "Release-initial" and check it out to "~/path/to/old"

directory by the following.

$ cvs rtag -b -r Release-initial Release-initial-bugfixes module1

$ cd ~/path/to

$ cvs co -r Release-initial-bugfixes -d old module1

$ cd old

Dica

Page 666: Referências Debian

Use "-D 2005-12-20" (ISO 8601 date format) instead of "-r

Release-initial" to specify particular date as the branch point.

Work on this local source tree having the sticky tag

"Release-initial-bugfixes" which is based on the original

version.

Work on this branch by yourself … until someone else joins to

this "Release-initial-bugfixes" branch.

Sync with files modified by others on this branch while creating

new directories as needed by the following.

$ cvs up -d

Edit files to fix conflicts as needed.

Verifique as alterações no CVS com o seguinte.

$ cvs ci -m "checked into this branch"

Update the local tree by HEAD of main while removing sticky tag

("-A") and without keyword expansion ("-kk") by the following.

$ cvs up -d -kk -A

Update the local tree (content = HEAD of main) by merging from

the "Release-initial-bugfixes" branch and without keyword

expansion by the following.

Page 667: Referências Debian

$ cvs up -d -kk -j Release-initial-bugfixes

Corrigir conflitos com o editor.

Verifique as alterações no CVS com o seguinte.

$ cvs ci -m "merged Release-initial-bugfixes"

Criar arquivo com o seguinte.

$ cd ..

$ mv old old-module1-bugfixes

$ tar -cvzf old-module1-bugfixes.tar.gz old-module1-bugfixes

$ rm -rf old-module1-bugfixes

Dica

"cvs up" command can take "-d" option to create new directories

and "-P" option to prune empty directories.

Dica

You can checkout only a sub directory of "module1" by providing

its name as "cvs co module1/subdir".

Tabela 10.18. Notable options for CVS commands (use as first

argument(s) to cvs(1))

Page 668: Referências Debian

┌─────┬──────────────────────────────────────────────┐

opção significado │ │ │

├─────┼──────────────────────────────────────────────┤

-n dry run, no effect │ │ │

├─────┼──────────────────────────────────────────────┤

-t display messages showing steps of cvs activity│ │ │

└─────┴──────────────────────────────────────────────┘

10.7.8. Ficheiros mais recentes do CVS

To get the latest files from CVS, use "tomorrow" by the

following.

$ cvs ex -D tomorrow module_name

10.7.9. Administração do CVS

Add module alias "mx" to a CVS project (local server) by the

following.

$ export CVSROOT=/srv/cvs/project

$ cvs co CVSROOT/modules

$ cd CVSROOT

$ echo "mx -a module1" >>modules

$ cvs ci -m "Now mx is an alias for module1"

$ cvs release -d .

Now, you can check out "module1" (alias: "mx") from CVS to "new"

Page 669: Referências Debian

directory by the following.

$ cvs co -d new mx

$ cd new

Nota

In order to perform above procedure, you should have appropriate

file permissions.

10.7.10. Execution bit for CVS checkout

When you checkout files from CVS, their execution permission bit

is retained.

Whenever you see execution permission problems in a checked out

file, e.g. "filename", change its permission in the

corresponding CVS repository by the following to fix it.

# chmod ugo-x nome_de_ficheiro

10.8. Subversion

Subversion is a recent-generation version control system

replacing older CVS. It has most of CVS's features except tags

and branches.

You need to install subversion, libapache2-svn and

subversion-tools packages to set up a Subversion server.

Page 670: Referências Debian

10.8.1. Configuration of Subversion repository

Currently, the subversion package does not set up a repository,

so one must set it up manually. One possible location for a

repository is in "/srv/svn/project".

Crie um directório com o seguinte.

# mkdir -p /srv/svn/project

Crie a base de dados do repositório com o seguinte.

# svnadmin create /srv/svn/project

10.8.2. Access to Subversion via Apache2 server

If you only access Subversion repository via Apache2 server, you

just need to make the repository only writable by the WWW server

by the following.

# chown -R www-data:www-data /srv/svn/project

Add (or uncomment) the following in "/etc/apache2/mods-available

/dav_svn.conf" to allow access to the repository via user

authentication.

<Location /project>

DAV svn

Page 671: Referências Debian

SVNPath /srv/svn/project

AuthType Basic

AuthName "Subversion repository"

AuthUserFile /etc/subversion/passwd

<LimitExcept GET PROPFIND OPTIONS REPORT>

Require valid-user

</LimitExcept>

</Location>

Crie um ficheiro de autenticação de utilizador com o comando com

o seguinte.

# htpasswd2 -c /etc/subversion/passwd algum_nome_de_utilizador

Reiniciar o Apache2

Your new Subversion repository is accessible at URL "http://

localhost/project" and "http://example.com/project" from svn(1)

(assuming your URL of web server is "http://example.com/").

10.8.3. Acesso local ao Subversion pelo grupo

The following sets up Subversion repository for the local access

by a group, e.g. project.

# chmod 2775 /srv/svn/project

# chown -R root:src /srv/svn/project

# chmod -R ug+rwX /srv/svn/project

Page 672: Referências Debian

Your new Subversion repository is group accessible at URL "file:

///localhost/srv/svn/project" or "file:///srv/svn/project" from

svn(1) for local users belonging to project group. You must run

commands, such as svn, svnserve, svnlook, and svnadmin under

"umask 002" to ensure group access.

10.8.4. Acesso remoto ao Subversion via SSH

A group accessible Subversion repository is at URL "example.com:

/srv/svn/project" for SSH, you can access it from svn(1) at URL

"svn+ssh://example.com:/srv/svn/project".

10.8.5. Estrutura de directórios do Subversion

Many projects uses directory tree similar to the following for

Subversion to compensate its lack of branches and tags.

----- module1

| |-- branches

| |-- tags

| | |-- release-1.0

| | `-- release-2.0

| |

| `-- trunk

| |-- file1

| |-- file2

| `-- file3

|

`-- module2

Page 673: Referências Debian

Dica

You must use "svn copy …" command to mark branches and tags.

This ensures Subversion to record modification history of files

properly and saves storage spaces.

10.8.6. importar uma nova fonte para o Subversion

Crie uma nova localização de árvore fonte local em "~/caminho/

para/module1" com o seguinte.

$ mkdir -p ~/caminho/para/module1; cd ~/caminho/para/module1

Populate a new local source tree under "~/path/to/module1" with

files.

Import it to Subversion with the following parameters.

Module name: "module1"●

Subversion site URL: "file:///srv/svn/project"●

Subversion directory: "module1/trunk"●

Subversion tag: "module1/tags/Release-initial"●

$ cd ~/path/to/module1

$ svn import file:///srv/svn/project/module1/trunk -m "Start module1"

$ svn cp file:///srv/svn/project/module1/trunk file:///srv/svn/project/module1/tags/Release-initial

Page 674: Referências Debian

Alternativamente, pelo seguinte.

$ svn import ~/path/to/module1 file:///srv/svn/project/module1/trunk -m "Start module1"

$ svn cp file:///srv/svn/project/module1/trunk file:///srv/svn/project/module1/tags/Release-initial

Dica

You can replace URLs such as "file:///…" by any other URL

formats such as "http://…" and "svn+ssh://…".

10.8.7. Fluxo de trabalho do Subversion

Here is an example of typical work flow using Subversion with

its native client.

Dica

Client commands offered by the git-svn package may offer

alternative work flow of Subversion using the git command. See

Secção 10.9.4, “Git para o repositório Subversion”.

Check all available modules from Subversion project pointed by

URL "file:///srv/svn/project" by the following.

$ svn list file:///srv/svn/project

module1

module2

...

Page 675: Referências Debian

Checkout "module1/trunk" to a directory "module1" by the

following.

$ cd ~/path/to

$ svn co file:///srv/svn/project/module1/trunk module1

$ cd module1

Faça as alterações necessárias ao conteúdo.

Check changes by making "diff -u [repository] [local]"

equivalent by the following.

$ svn diff

You find that you broke some file "file_to_undo" severely but

other files are fine.

Overwrite "file_to_undo" file with the clean copy from

Subversion by the following.

$ svn revert ficheiro_para_desfazer

Save the updated local source tree to Subversion by the

following.

$ svn ci -m "Describe change"

Create and add "file_to_add" file to Subversion by the

Page 676: Referências Debian

following.

$ vi file_to_add

$ svn add file_to_add

$ svn ci -m "Added file_to_add"

Merge the latest version from Subversion by the following.

$ svn up

Watch out for lines starting with "C filename" which indicates

conflicting changes.

Look for unmodified code in, e.g., "filename.r6", "filename.r9",

and "filename.mine".

Search for "<<<<<<<" and ">>>>>>>" in files for conflicting

changes.

Edit files to fix conflicts as needed.

Adicione uma etiqueta de lançamento "Release-1" com o seguinte.

$ svn ci -m "last commit for Release-1"

$ svn cp file:///srv/svn/project/module1/trunk file:///srv/svn/project/module1/tags/Release-1

Continuar a editar.

Page 677: Referências Debian

Remova a etiqueta de lançamento "Release-1" com o seguinte.

$ svn rm file:///srv/svn/project/module1/tags/Release-1

Check in changes to Subversion by the following.

$ svn ci -m "real last commit for Release-1"

Re-add the release tag "Release-1" from updated Subversion HEAD

of trunk by the following.

$ svn cp file:///srv/svn/project/module1/trunk file:///srv/svn/project/module1/tags/Release-1

Create a branch with a path "module1/branches/

Release-initial-bugfixes" from the original version pointed by

the path "module1/tags/Release-initial" and check it out to "~/

path/to/old" directory by the following.

$ svn cp file:///srv/svn/project/module1/tags/Release-initial file:///srv/svn/project/module1/branches/Release-initial-bugfixes

$ cd ~/path/to

$ svn co file:///srv/svn/project/module1/branches/Release-initial-bugfixes old

$ cd old

Dica

Use "module1/trunk@{2005-12-20}" (ISO 8601 date format) instead

of "module1/tags/Release-initial" to specify particular date as

the branch point.

Page 678: Referências Debian

Work on this local source tree pointing to branch

"Release-initial-bugfixes" which is based on the original

version.

Work on this branch by yourself … until someone else joins to

this "Release-initial-bugfixes" branch.

Sync with files modified by others on this branch by the

following.

$ svn up

Edit files to fix conflicts as needed.

Check in changes to Subversion by the following.

$ svn ci -m "checked into this branch"

Update the local tree with HEAD of trunk by the following.

$ svn switch file:///srv/svn/project/module1/trunk

Update the local tree (content = HEAD of trunk) by merging from

the "Release-initial-bugfixes" branch by the following.

$ svn merge file:///srv/svn/project/module1/branches/Release-initial-bugfixes

Corrigir conflitos com o editor.

Page 679: Referências Debian

Check in changes to Subversion by the following.

$ svn ci -m "merged Release-initial-bugfixes"

Criar arquivo com o seguinte.

$ cd ..

$ mv old old-module1-bugfixes

$ tar -cvzf old-module1-bugfixes.tar.gz old-module1-bugfixes

$ rm -rf old-module1-bugfixes

Dica

You can replace URLs such as "file:///…" by any other URL

formats such as "http://…" and "svn+ssh://…".

Dica

You can checkout only a sub directory of "module1" by providing

its name as "svn co file:///srv/svn/project/module1/trunk/subdir

module1/subdir", etc.

Tabela 10.19. Notable options for Subversion commands (use as

first argument(s) to svn(1))

┌─────────┬────────────────────────────────────────────────┐

opção significado │ │ │

Page 680: Referências Debian

├─────────┼────────────────────────────────────────────────┤

--dry-run dry run, no effect │ │ │

├─────────┼────────────────────────────────────────────────┤

-v mostra mensagens detalhadas da actividade do svn│ │ │

└─────────┴────────────────────────────────────────────────┘

10.9. Git

Git can do everything for both local and remote source code

management. This means that you can record the source code

changes without needing network connectivity to the remote

repository.

10.9.1. Configuração do cliente Git

You may wish to set several global configuration in "~

/.gitconfig" such as your name and email address used by Git by

the following.

$ git config --global user.name "Name Surname"

$ git config --global user.email [email protected]

If you are too used to CVS or Subversion commands, you may wish

to set several command aliases by the following.

$ git config --global alias.ci "commit -a"

Page 681: Referências Debian

$ git config --global alias.co checkout

Você pode verificar a sua configuração global com o seguinte.

$ git config --global --list

10.9.2. Referências do Git

Veja o seguinte.

manpage: git(1) (/usr/share/doc/git-doc/git.html)●

Git User's Manual (/usr/share/doc/git-doc/user-manual.html)●

A tutorial introduction to git (/usr/share/doc/git-doc/●

gittutorial.html)

A tutorial introduction to git: part two (/usr/share/doc/●

git-doc/gittutorial-2.html)

Everyday GIT With 20 Commands Or So (/usr/share/doc/git-doc/●

everyday.html)

git for CVS users (/usr/share/doc/git-doc/●

gitcvs-migration.html)

This also describes how to set up server like CVS and○

extract old data from CVS into Git.

Other git resources available on the web●

Git - SVN Crash Course○

Git Magic (/usr/share/doc/gitmagic/html/index.html)○

git-gui(1) and gitk(1) commands make using Git very easy.

Page 682: Referências Debian

Atenção

Do not use the tag string with spaces in it even if some tools

such as gitk(1) allow you to use it. It may choke some other git

commands.

10.9.3. Comandos do Git

Even if your upstream uses different VCS, it may be good idea to

use git(1) for local activity since you can manage your local

copy of source tree without the network connection to the

upstream. Here are some packages and commands used with git(1).

Tabela 10.20. Lista de pacotes e comandos relacionados com o git

┌───────────────────┬────────────────┬───────┬───────┬─────────────┐

comando pacote popcon tamanho descrição │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

documentação │ │ │ │ │ │

N/D git-doc * I:3 7436 oficial para │ │ │ │ │ │

o Git │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

"Git Magic", │ │ │ │ │ │

N/D gitmagic * I:0.3 920 easier to │ │ │ │ │ │

understand │ │ │ │ │ │

guide for Git│ │ │ │ │ │

Page 683: Referências Debian

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

Git, the │ │ │ │ │ │

fast, │ │ │ │ │ │

V:5, scalable, │ │ │ │ │ │

git(7) git * I:17 10632 distributed │ │ │ │ │ │

revision │ │ │ │ │ │

control │ │ │ │ │ │

system │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

GUI Git │ │ │ │ │ │

gitk(1) gitk * V:0.8, 900 repository │ │ │ │ │ │

I:4 browser with │ │ │ │ │ │

history │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

git-gui(1) git-gui * V:0.3, 1612 GUI for Git │ │ │ │ │ │

I:2 (No history) │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

import the │ │ │ │ │ │

git-svnimport(1) git-svn * V:0.5, 552 data out of │ │ │ │ │ │

I:3 Subversion │ │ │ │ │ │

into Git │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

provide │ │ │ │ │ │

bidirectional│ │ │ │ │ │

git-svn(1) git-svn * V:0.5, 552 operation │ │ │ │ │ │

I:3 between the │ │ │ │ │ │

Page 684: Referências Debian

Subversion │ │ │ │ │ │

and Git │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

V:0.17, import the │ │ │ │ │ │

git-cvsimport(1) git-cvs * I:1.6 676 data out of │ │ │ │ │ │

CVS into Git │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

export a │ │ │ │ │ │

git-cvsexportcommit git-cvs * V:0.17, 676 commit to a │ │ │ │ │ │

(1) I:1.6 CVS checkout │ │ │ │ │ │

from Git │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

V:0.17, CVS server │ │ │ │ │ │

git-cvsserver(1) git-cvs * I:1.6 676 emulator for │ │ │ │ │ │

Git │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

send a │ │ │ │ │ │

V:0.12, collection of│ │ │ │ │ │

git-send-email(1) git-email * I:1.7 404 patches as │ │ │ │ │ │

email from │ │ │ │ │ │

the Git │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

V:0.07, quilt on top │ │ │ │ │ │

stg(1) stgit * I:0.7 1864 of git │ │ │ │ │ │

(Python) │ │ │ │ │ │

Page 685: Referências Debian

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

automate the │ │ │ │ │ │

git-buildpackage(1) git-buildpackage V:0.2, 596 Debian │ │ │ │ │ │

* I:1.1 packaging │ │ │ │ │ │

with the Git │ │ │ │ │ │

├───────────────────┼────────────────┼───────┼───────┼─────────────┤

V:0.01, quilt on top │ │ │ │ │ │

guilt(7) guilt * I:0.11 336 of git (SH/ │ │ │ │ │ │

AWK/SED/…) │ │ │ │ │ │

└───────────────────┴────────────────┴───────┴───────┴─────────────┘

Dica

With git(1), you work on a local branch with many commits and

use something like "git rebase -i master" to reorganize change

history later. This enables you to make clean change history.

See git-rebase(1) and git-cherry-pick(1).

Dica

When you want to go back to a clean working directory without

loosing the current state of the working directory, you can use

"git stash". See git-stash(1).

10.9.4. Git para o repositório Subversion

Page 686: Referências Debian

You can check out a Subversion repository at "svn+ssh://

svn.example.org/project/module/trunk" to a local Git repository

at "./dest" and commit back to the Subversion repository. E.g.:

$ git svn clone -s -rHEAD svn+ssh://svn.example.org/project dest

$ cd dest

... make changes

$ git commit -a

... keep working locally with git

$ git svn dcommit

Dica

The use of "-rHEAD" enables us to avoid cloning entire

historical contents from the Subversion repository.

10.9.5. Git para gravar o histórico de configuração

You can manually record chronological history of configuration

using Git tools. Here is a simple example for your practice to

record "/etc/apt/" contents.

$ cd /etc/apt/

$ sudo git init

$ sudo chmod 700 .git

$ sudo git add .

$ sudo git commit -a

Cometer configuração com descrição

Page 687: Referências Debian

Fazer modificações nos ficheiros de configuração.

$ cd /etc/apt/

$ sudo git commit -a

Cometer a configuração com descrição e continuar com a sua vida.

$ cd /etc/apt/

$ sudo gitk --all

You have full configuration history with you.

Nota

sudo(8) is needed to work with any file permissions of

configuration data. For user configuration data, you may skip

sudo.

Nota

The "chmod 700 .git" command in the above example is needed to

protect archive data from unauthorized read access.

Dica

For more complete setup for recording configuration history,

please look for the etckeeper package: Secção 9.2.10, “Gravar

alterações em ficheiros de configuração”.

Page 688: Referências Debian

Capítulo 11. Conversão de dados

Tools and tips for converting data formats on the Debian system

are described.

Standard based tools are in very good shape but support for

proprietary data formats are limited.

11.1. Ferramentas de conversão de dados em texto

Os seguinte pacotes para a conversão de dados de texto

saltaram-me à vista.

Tabela 11.1. Lista de ferramentas de conversão de dados em texto

┌────────┬───────┬───────┬───────────┬─────────────────────────┐

pacote popcon tamanho palavra descrição │ │ │ │ │ │

chave │ │ │ │ │ │

├────────┼───────┼───────┼───────────┼─────────────────────────┤

V:97, conjunto e converter codificação de │ │ │ │ │ │

libc6 * I:99 10012 caracteres texto entre locales por │ │ │ │ │ │

(charset) iconv(1) (fundamental) │ │ │ │ │ │

├────────┼───────┼───────┼───────────┼─────────────────────────┤

text encoding converter │ │ │ │ │ │

recode * V:1.5, 772 charset+eol between locales │ │ │ │ │ │

I:7 (versatile, more aliases │ │ │ │ │ │

Page 689: Referências Debian

and features) │ │ │ │ │ │

├────────┼───────┼───────┼───────────┼─────────────────────────┤

konwert V:0.4, conjunto e conversor de codificação │ │ │ │ │ │

* I:4 192 caracteres de texto entre locales │ │ │ │ │ │

(charset) (imaginativo) │ │ │ │ │ │

├────────┼───────┼───────┼───────────┼─────────────────────────┤

V:0.2, conjunto e tradutor de conjunto de │ │ │ │ │ │

nkf * I:2 300 caracteres caracteres para Japonês │ │ │ │ │ │

(charset) │ │ │ │ │ │

├────────┼───────┼───────┼───────────┼─────────────────────────┤

V:0.02, conjunto e tradutor de conjunto de │ │ │ │ │ │

tcs * I:0.14 544 caracteres caracteres │ │ │ │ │ │

(charset) │ │ │ │ │ │

├────────┼───────┼───────┼───────────┼─────────────────────────┤

unaccent V:0.01, conjunto e substitui letras │ │ │ │ │ │

* I:0.09 76 caracteres acentuadas pelo seu │ │ │ │ │ │

(charset) equivalente não acentuado│ │ │ │ │ │

├────────┼───────┼───────┼───────────┼─────────────────────────┤

tofrodos V:1.1, conversor de formato de │ │ │ │ │ │

* I:7 48 eol texto entre DOS e Unix: │ │ │ │ │ │

de dos(1) e para dos(1) │ │ │ │ │ │

├────────┼───────┼───────┼───────────┼─────────────────────────┤

conversor de formato de │ │ │ │ │ │

macutils V:0.05, 320 eol texto entre Macintosh e │ │ │ │ │ │

* I:0.5 Unix: de mac(1) e para │ │ │ │ │ │

Page 690: Referências Debian

mac(1) │ │ │ │ │ │

└────────┴───────┴───────┴───────────┴─────────────────────────┘

11.1.1. Converter um ficheiro de texto com o iconv

Dica

iconv(1) é disponibilizado como parte do pacote libc6 e está

sempre disponível em praticamente todos os sistemas para

converter a codificação de caracteres.

Você pode converter a codificação de um ficheiro de texto com o

iconv(1) com o seguinte.

$ iconv -f codificação1 -t codificação2 entrada.txt >saída.txt

Os valores de codificação são sensíveis a maiúsculas/minúsculas

e ignoram "-" e "_" para correspondência. As codificações

suportadas podem ser verificadas pelo comando "iconv -l"

Tabela 11.2. Lista de valores de codificação e a sua utilização

┌───────────┬──────────────────────────────────────────────────┐

valor de utilização │ │ │

codificação │ │ │

├───────────┼──────────────────────────────────────────────────┤

Page 691: Referências Debian

ASCII. American Standard Code for Information Interchange│ │ │

, 7 bit code w/o accented characters │ │ │

├───────────┼──────────────────────────────────────────────────┤

UTF-8 standard multilingue actual para todos os sistemas│ │ │

operativos modernos │ │ │

├───────────┼──────────────────────────────────────────────────┤

ISO-8859-1 antigo standard para linguagens da Europa │ │ │

ocidental, ASCII + caracteres acentuados │ │ │

├───────────┼──────────────────────────────────────────────────┤

ISO-8859-2 antigo standard para linguagens da Europa │ │ │

oriental, ASCII + caracteres acentuados │ │ │

├───────────┼──────────────────────────────────────────────────┤

ISO-8859-15 antigo standard para linguagens da Europa │ │ │

ocidental, o ISO-8859-1 com o símbolo do euro │ │ │

├───────────┼──────────────────────────────────────────────────┤

code page 850, Microsoft DOS characters with │ │ │

CP850 graphics for western European languages, │ │ │

ISO-8859-1 variant │ │ │

├───────────┼──────────────────────────────────────────────────┤

CP932 code page 932, Microsoft Windows style Shift-JIS │ │ │

variant for Japanese │ │ │

├───────────┼──────────────────────────────────────────────────┤

CP936 code page 936, Microsoft Windows style GB2312, GBK│ │ │

or GB18030 variant for Simplified Chinese │ │ │

Page 692: Referências Debian

├───────────┼──────────────────────────────────────────────────┤

CP949 code page 949, Microsoft Windows style EUC-KR or │ │ │

Unified Hangul Code variant for Korean │ │ │

├───────────┼──────────────────────────────────────────────────┤

CP950 code page 950, Microsoft Windows style Big5 │ │ │

variant for Traditional Chinese │ │ │

├───────────┼──────────────────────────────────────────────────┤

CP1251 code page 1251, Microsoft Windows style encoding │ │ │

for the Cyrillic alphabet │ │ │

├───────────┼──────────────────────────────────────────────────┤

CP1252 code page 1252, Microsoft Windows style │ │ │

ISO-8859-15 variant for western European languages│ │ │

├───────────┼──────────────────────────────────────────────────┤

KOI8-R old Russian UNIX standard for the Cyrillic │ │ │

alphabet │ │ │

├───────────┼──────────────────────────────────────────────────┤

ISO-2022-JP standard encoding for Japanese email which uses │ │ │

only 7 bit codes │ │ │

├───────────┼──────────────────────────────────────────────────┤

eucJP old Japanese UNIX standard 8 bit code and │ │ │

completely different from Shift-JIS │ │ │

├───────────┼──────────────────────────────────────────────────┤

Shift-JIS JIS X 0208 Appendix 1 standard for Japanese (see │ │ │

CP932) │ │ │

Page 693: Referências Debian

└───────────┴──────────────────────────────────────────────────┘

Nota

Some encodings are only supported for the data conversion and

are not used as locale values (Secção 8.3.1, “Bases de

codificação”).

For character sets which fit in single byte such as ASCII and

ISO-8859 character sets, the character encoding means almost the

same thing as the character set.

For character sets with many characters such as JIS X 0213 for

Japanese or Universal Character Set (UCS, Unicode, ISO-10646-1)

for practically all languages, there are many encoding schemes

to fit them into the sequence of the byte data.

EUC and ISO/IEC 2022 (also known as JIS X 0202) for Japanese●

UTF-8, UTF-16/UCS-2 and UTF-32/UCS-4 for Unicode●

For these, there are clear differentiations between the

character set and the character encoding.

The code page is used as the synonym to the character encoding

tables for some vendor specific ones.

Nota

Page 694: Referências Debian

Please note most encoding systems share the same code with ASCII

for the 7 bit characters. But there are some exceptions. If you

are converting old Japanese C programs and URLs data from the

casually-called shift-JIS encoding format to UTF-8 format, use

"CP932" as the encoding name instead of "shift-JIS" to get the

expected results: 0x5C → "\" and 0x7E → "~" . Otherwise, these

are converted to wrong characters.

Dica

recode(1) may be used too and offers more than the combined

functionality of iconv(1), fromdos(1), todos(1), frommac(1), and

tomac(1). For more, see "info recode".

11.1.2. Verifica ficheiro se é UTF-8 com o iconv

You can check if a text file is encoded in UTF-8 with iconv(1)

by the following.

$ iconv -f utf8 -t utf8 input.txt >/dev/null || echo "non-UTF-8 found"

Dica

Use "--verbose" option in the above example to find the first

non-UTF-8 character.

11.1.3. Converter os nomes dos ficheiros com o iconv

Page 695: Referências Debian

Aqui está um script exemplo para converter a codificação dos

nomes de ficheiros daqueles criados sob sistemas operativos

antigos para os modernos de UTF-8 num único directório.

#!/bin/sh

ENCDN=iso-8859-1

for x in *;

do

mv "$x" $(echo "$x" | iconv -f $ENCDN -t utf-8)

done

The "$ENCDN" variable should be set by the encoding value in

Tabela 11.2, “Lista de valores de codificação e a sua

utilização”.

For more complicated case, please mount a filesystem (e.g. a

partition on a disk drive) containing such file names with

proper encoding as the mount(8) option (see Secção 8.3.6,

“Codificação de nomes de ficheiros”) and copy its entire

contents to another filesystem mounted as UTF-8 with "cp -a"

command.

11.1.4. conversão EOL

The text file format, specifically the end-of-line (EOL) code,

is dependent on the platform.

Tabela 11.3. Lista de estilos EOL para diferentes plataformas

Page 696: Referências Debian

┌──────────────────┬──────────┬────────┬───────┬───────────┐

plataforma código EOL controle decimal hexadecimal│ │ │ │ │ │

├──────────────────┼──────────┼────────┼───────┼───────────┤

Debian (unix) LF ^J 10 0A │ │ │ │ │ │

├──────────────────┼──────────┼────────┼───────┼───────────┤

MSDOS e Windows CR-LF ^M^J 13 10 0D 0A │ │ │ │ │ │

├──────────────────┼──────────┼────────┼───────┼───────────┤

Macintosh da Apple CR ^M 13 0D │ │ │ │ │ │

└──────────────────┴──────────┴────────┴───────┴───────────┘

The EOL format conversion programs, fromdos(1), todos(1),

frommac(1), and tomac(1), are quite handy. recode(1) is also

useful.

Nota

Some data on the Debian system, such as the wiki page data for

the python-moinmoin package, use MSDOS style CR-LF as the EOL

code. So the above rule is just a general rule.

Nota

Most editors (eg. vim, emacs, gedit, …) can handle files in

MSDOS style EOL transparently.

Page 697: Referências Debian

Dica

The use of "sed -e '/\r$/!s/$/\r/'" instead of todos(1) is

better when you want to unify the EOL style to the MSDOS style

from the mixed MSDOS and Unix style. (e.g., after merging 2

MSDOS style files with diff3(1).) This is because todos adds CR

to all lines.

11.1.5. Conversão de TAB

Existem alguns programas populares especializados para converter

os códigos de tab.

Tabela 11.4. List of TAB conversion commands from bsdmainutils

and coreutils packages

┌───────────────────────────────┬────────────┬─────────┐

função bsdmainutils coreutils│ │ │ │

├───────────────────────────────┼────────────┼─────────┤

expande tab para espaços "col -x" expand │ │ │ │

├───────────────────────────────┼────────────┼─────────┤

contrai tab a partir de espaços "col -h" unexpand │ │ │ │

└───────────────────────────────┴────────────┴─────────┘

indent(1) from the indent package completely reformats

whitespaces in the C program.

Editor programs such as vim and emacs can be used for TAB

Page 698: Referências Debian

conversion, too. For example with vim, you can expand TAB with

":set expandtab" and ":%retab" command sequence. You can revert

this with ":set noexpandtab" and ":%retab!" command sequence.

11.1.6. Editores com auto-conversão

Intelligent modern editors such as the vim program are quite

smart and copes well with any encoding systems and any file

formats. You should use these editors under the UTF-8 locale in

the UTF-8 capable console for the best compatibility.

An old western European Unix text file, "u-file.txt", stored in

the latin1 (iso-8859-1) encoding can be edited simply with vim

by the following.

$ vim u-file.txt

This is possible since the auto detection mechanism of the file

encoding in vim assumes the UTF-8 encoding first and, if it

fails, assumes it to be latin1.

An old Polish Unix text file, "pu-file.txt", stored in the

latin2 (iso-8859-2) encoding can be edited with vim by the

following.

$ vim '+e ++enc=latin2 pu-file.txt'

An old Japanese unix text file, "ju-file.txt", stored in the

eucJP encoding can be edited with vim by the following.

Page 699: Referências Debian

$ vim '+e ++enc=eucJP ju-file.txt'

An old Japanese MS-Windows text file, "jw-file.txt", stored in

the so called shift-JIS encoding (more precisely: CP932) can be

edited with vim by the following.

$ vim '+e ++enc=CP932 ++ff=dos jw-file.txt'

When a file is opened with "++enc" and "++ff" options, ":w" in

the Vim command line stores it in the original format and

overwrite the original file. You can also specify the saving

format and the file name in the Vim command line, e.g., ":w

++enc=utf8 new.txt".

Please refer to the mbyte.txt "multi-byte text support" in vim

on-line help and Tabela 11.2, “Lista de valores de codificação e

a sua utilização” for locale values used with "++enc".

The emacs family of programs can perform the equivalent

functions.

11.1.7. Extracção de texto simples

The following reads a web page into a text file. This is very

useful when copying configurations off the Web or applying basic

Unix text tools such as grep(1) on the web page.

$ w3m -dump http://www.remote-site.com/help-info.html >textfile

Page 700: Referências Debian

Similarly, you can extract plain text data from other formats

using the following.

Tabela 11.5. Lista de ferramentas para extracção de dados de

texto simples

┌─────────┬───────┬───────┬────────────────┬───────────────────┐

pacote popcon tamanho palavra chave função │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

V:24, Conversor de HTML │ │ │ │ │ │

w3m * I:84 1992 html→texto para texto com o │ │ │ │ │ │

comando "w3m -dump"│ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

html2text V:15, Conversor de HTML │ │ │ │ │ │

* I:37 248 html→texto para texto avançado│ │ │ │ │ │

(ISO 8859-1) │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

Conversor de HTML │ │ │ │ │ │

lynx * I:22 252 html→texto para texto com o │ │ │ │ │ │

comando "lynx │ │ │ │ │ │

-dump" │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

Conversor de HTML │ │ │ │ │ │

elinks * V:2, 1448 html→texto para texto com o │ │ │ │ │ │

I:5 comando "elinks │ │ │ │ │ │

Page 701: Referências Debian

-dump" │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

Conversor de HTML │ │ │ │ │ │

links * V:3, 1380 html→texto para texto com o │ │ │ │ │ │

I:9 comando "links │ │ │ │ │ │

-dump" │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

Conversor de HTML │ │ │ │ │ │

links2 * V:0.7, 3288 html→texto para texto com o │ │ │ │ │ │

I:3 comando "links2 │ │ │ │ │ │

-dump" │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

antiword V:1.3, converte ficheiros │ │ │ │ │ │

* I:2 796 MSWord→texto,ps do MSWord para │ │ │ │ │ │

texto simples ou ps│ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

converte ficheiros │ │ │ │ │ │

catdoc * V:1.0, 2580 MSWord→texto,TeX do MSWord para │ │ │ │ │ │

I:2 texto simples ou │ │ │ │ │ │

TeX │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

pstotext V:0.8, extrai texto de │ │ │ │ │ │

* I:1.4 148 ps/pdf→texto ficheiros │ │ │ │ │ │

PostScript e PDF │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

Page 702: Referências Debian

V:0.02, remove as etiquetas│ │ │ │ │ │

unhtml * I:0.14 76 html→texto de marcas de um │ │ │ │ │ │

ficheiro HTML │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

V:0.8, conversor de texto │ │ │ │ │ │

odt2txt * I:1.4 100 odt→texto do OpenDocument │ │ │ │ │ │

para texto │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────┼───────────────────┤

WordPerfect to │ │ │ │ │ │

wpd2sxw * V:0.02, 156 WordPerfect→sxw OpenOffice.org/ │ │ │ │ │ │

I:0.13 StarOffice writer │ │ │ │ │ │

document converter │ │ │ │ │ │

└─────────┴───────┴───────┴────────────────┴───────────────────┘

11.1.8. Highlighting and formatting plain text data

You can highlight and format plain text data by the following.

Tabela 11.6. List of tools to highlight plain text data

┌────────────────┬───────┬───────┬──────────────┬──────────────┐

pacote popcon tamanho palavra chave descrição │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

Vim MACRO to │ │ │ │ │ │

convert source│ │ │ │ │ │

Page 703: Referências Debian

V:3, code to HTML │ │ │ │ │ │

vim-runtime * I:38 25864 destaque with ":source │ │ │ │ │ │

$VIMRUNTIME/ │ │ │ │ │ │

syntax/ │ │ │ │ │ │

html.vim" │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

converter for │ │ │ │ │ │

V:0.05, the C program │ │ │ │ │ │

cxref * I:0.4 1252 c→html to latex and │ │ │ │ │ │

HTML (C │ │ │ │ │ │

language) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

convert many │ │ │ │ │ │

src2tex * V:0.03, 1968 destaque source codes │ │ │ │ │ │

I:0.2 to TeX (C │ │ │ │ │ │

language) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

convert many │ │ │ │ │ │

source codes │ │ │ │ │ │

to HTML, │ │ │ │ │ │

XHTML, LaTeX, │ │ │ │ │ │

source-highlight V:0.14, 2164 destaque Texinfo, ANSI │ │ │ │ │ │

* I:1.1 color escape │ │ │ │ │ │

sequences and │ │ │ │ │ │

DocBook files │ │ │ │ │ │

with highlight│ │ │ │ │ │

(C++) │ │ │ │ │ │

Page 704: Referências Debian

├────────────────┼───────┼───────┼──────────────┼──────────────┤

convert many │ │ │ │ │ │

source codes │ │ │ │ │ │

to HTML, │ │ │ │ │ │

highlight * V:0.2, 756 destaque XHTML, RTF, │ │ │ │ │ │

I:1.3 LaTeX, TeX or │ │ │ │ │ │

XSL-FO files │ │ │ │ │ │

with highlight│ │ │ │ │ │

(C++) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

generic │ │ │ │ │ │

grc * V:0.05, 164 texto→cor colouriser for│ │ │ │ │ │

I:0.12 everything │ │ │ │ │ │

(Python) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

V:0.08, text to HTML │ │ │ │ │ │

txt2html * I:0.5 296 texto→html converter │ │ │ │ │ │

(Perl) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

markdown text │ │ │ │ │ │

markdown * V:0.07, 96 texto→html document │ │ │ │ │ │

I:0.4 formatter to │ │ │ │ │ │

(X)HTML (Perl)│ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

AsciiDoc text │ │ │ │ │ │

V:0.15, document │ │ │ │ │ │

Page 705: Referências Debian

asciidoc * I:1.1 3028 texto→qualquer formatter to │ │ │ │ │ │

XML/HTML │ │ │ │ │ │

(Python) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

ReStructured │ │ │ │ │ │

python-docutils V:0.4, 5740 texto→qualquer Text document │ │ │ │ │ │

* I:3 formatter to │ │ │ │ │ │

XML (Python) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

document │ │ │ │ │ │

conversion │ │ │ │ │ │

from text to │ │ │ │ │ │

HTML, SGML, │ │ │ │ │ │

txt2tags * V:0.06, 1028 texto→qualquer LaTeX, man │ │ │ │ │ │

I:0.3 page, │ │ │ │ │ │

MoinMoin, │ │ │ │ │ │

Magic Point │ │ │ │ │ │

and PageMaker │ │ │ │ │ │

(Python) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

universal │ │ │ │ │ │

document - │ │ │ │ │ │

udo * V:0.01, 556 texto→qualquer text │ │ │ │ │ │

I:0.07 processing │ │ │ │ │ │

utility (C │ │ │ │ │ │

language) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

Page 706: Referências Debian

document │ │ │ │ │ │

converter from│ │ │ │ │ │

stx2any * V:0.00, 484 texto→qualquer structured │ │ │ │ │ │

I:0.04 plain text to │ │ │ │ │ │

other formats │ │ │ │ │ │

(m4) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

document │ │ │ │ │ │

V:0.01, converter from│ │ │ │ │ │

rest2web * I:0.08 576 texto→html ReStructured │ │ │ │ │ │

Text to html │ │ │ │ │ │

(Python) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

"free form" │ │ │ │ │ │

aft * V:0.01, 340 texto→qualquer document │ │ │ │ │ │

I:0.06 preparation │ │ │ │ │ │

system (Perl) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

pre-document │ │ │ │ │ │

V:0.01, language and │ │ │ │ │ │

yodl * I:0.06 564 texto→qualquer tools to │ │ │ │ │ │

process it (C │ │ │ │ │ │

language) │ │ │ │ │ │

├────────────────┼───────┼───────┼──────────────┼──────────────┤

V:0.01, simple │ │ │ │ │ │

sdf * I:0.08 1940 texto→qualquer document │ │ │ │ │ │

parser (Perl) │ │ │ │ │ │

Page 707: Referências Debian

├────────────────┼───────┼───────┼──────────────┼──────────────┤

document │ │ │ │ │ │

structuring, │ │ │ │ │ │

sisu * V:0.01, 14384 texto→qualquer publishing and│ │ │ │ │ │

I:0.07 search │ │ │ │ │ │

framework │ │ │ │ │ │

(Ruby) │ │ │ │ │ │

└────────────────┴───────┴───────┴──────────────┴──────────────┘

11.2. Dados XML

The Extensible Markup Language (XML) is a markup language for

documents containing structured information.

See introductory information at XML.COM.

"O que é XML?"●

"O que é XSLT?"●

"O que é XSL-FO?"●

"O que é XLink?"●

11.2.1. Dicas básicas para XML

XML text looks somewhat like HTML. It enables us to manage

multiple formats of output for a document. One easy XML system

is the docbook-xsl package, which is used here.

Page 708: Referências Debian

Cada ficheiro XML começa com a declaração XML standard como o

seguinte.

<?xml version="1.0" encoding="UTF-8"?>

The basic syntax for one XML element is marked up as the

following.

<name attribute="value">content</name>

XML element with empty content is marked up in the following

short form.

<name attribute="value"/>

The "attribute="value"" in the above examples are optional.

A secção de comentários em XML está marcada como se segue.

<!-- comment -->

Other than adding markups, XML requires minor conversion to the

content using predefined entities for following characters.

Tabela 11.7. Lista de entidades predefinidas para XML

┌────────────────────┬──────────────────────────────┐

entidade predefinida character to be converted from│ │ │

├────────────────────┼──────────────────────────────┤

Page 709: Referências Debian

&quot; " : quote │ │ │

├────────────────────┼──────────────────────────────┤

&apos; ' : apostrophe │ │ │

├────────────────────┼──────────────────────────────┤

&lt; < : less-than │ │ │

├────────────────────┼──────────────────────────────┤

&gt; > : greater-than │ │ │

├────────────────────┼──────────────────────────────┤

&amp; & : ampersand │ │ │

└────────────────────┴──────────────────────────────┘

Cuidado

"<" or "&" can not be used in attributes or elements.

Nota

When SGML style user defined entities, e.g. "&some-tag:", are

used, the first definition wins over others. The entity

definition is expressed in "<!ENTITY some-tag "entity value">".

Nota

As long as the XML markup are done consistently with certain set

of the tag name (either some data as content or attribute

value), conversion to another XML is trivial task using

Extensible Stylesheet Language Transformations (XSLT).

Page 710: Referências Debian

11.2.2. Processamento de XML

There are many tools available to process XML files such as the

Extensible Stylesheet Language (XSL).

Basically, once you create well formed XML file, you can convert

it to any format using Extensible Stylesheet Language

Transformations (XSLT).

The Extensible Stylesheet Language for Formatting Object

(XSL-FO) is supposed to be solution for formatting. The fop

package is in the Debian contrib (not main) archive still. So

the LaTeX code is usually generated from XML using XSLT and the

LaTeX system is used to create printable file such as DVI,

PostScript, and PDF.

Tabela 11.8. Lista de ferramentas XML

┌───────────┬──────┬───────┬───────┬───────────────────────────┐

pacote popcon tamanho palavra descrição │ │ │ │ │ │

chave │ │ │ │ │ │

├───────────┼──────┼───────┼───────┼───────────────────────────┤

docbook-xml XML document type │ │ │ │ │ │

* I:47 2488 xml definition (DTD) for │ │ │ │ │ │

DocBook │ │ │ │ │ │

├───────────┼──────┼───────┼───────┼───────────────────────────┤

V:4, XSLT command line processor│ │ │ │ │ │

Page 711: Referências Debian

xsltproc * I:46 152 xslt (XML→ XML, HTML, plain │ │ │ │ │ │

text, etc.) │ │ │ │ │ │

├───────────┼──────┼───────┼───────┼───────────────────────────┤

XSL stylesheets for │ │ │ │ │ │

docbook-xsl V:0.5, 12792 xml/ processing DocBook XML to │ │ │ │ │ │

* I:7 xslt various output formats with│ │ │ │ │ │

XSLT │ │ │ │ │ │

├───────────┼──────┼───────┼───────┼───────────────────────────┤

xmlto * V:0.3, 268 xml/ XML-to-any converter with │ │ │ │ │ │

I:2 xslt XSLT │ │ │ │ │ │

├───────────┼──────┼───────┼───────┼───────────────────────────┤

V:0.2, xml/ convert Docbook files to │ │ │ │ │ │

dblatex * I:2 7340 xslt DVI, PostScript, PDF │ │ │ │ │ │

documents with XSLT │ │ │ │ │ │

├───────────┼──────┼───────┼───────┼───────────────────────────┤

fop * V:0.3, 2280 xml/ converter ficheiros Docbook│ │ │ │ │ │

I:2 xsl-fo XML para PDF │ │ │ │ │ │

└───────────┴──────┴───────┴───────┴───────────────────────────┘

Since XML is subset of Standard Generalized Markup Language

(SGML), it can be processed by the extensive tools available for

SGML, such as Document Style Semantics and Specification

Language (DSSSL).

Tabela 11.9. Lista de ferramentas DSSL

Page 712: Referências Debian

┌─────────────┬───────┬───────┬───────┬────────────────────────┐

pacote popcon tamanho palavra descrição │ │ │ │ │ │

chave │ │ │ │ │ │

├─────────────┼───────┼───────┼───────┼────────────────────────┤

V:0.4, ISO/IEC 10179:1996 │ │ │ │ │ │

openjade * I:3 1212 dsssl standard DSSSL processor│ │ │ │ │ │

(latest) │ │ │ │ │ │

├─────────────┼───────┼───────┼───────┼────────────────────────┤

V:0.02, ISO/IEC 10179:1996 │ │ │ │ │ │

openjade1.3 * I:0.14 2336 dsssl standard DSSSL processor│ │ │ │ │ │

(1.3.x series) │ │ │ │ │ │

├─────────────┼───────┼───────┼───────┼────────────────────────┤

V:0.3, James Clark's original │ │ │ │ │ │

jade * I:2 1056 dsssl DSSSL processor (1.2.x │ │ │ │ │ │

series) │ │ │ │ │ │

├─────────────┼───────┼───────┼───────┼────────────────────────┤

DSSSL stylesheets for │ │ │ │ │ │

docbook-dsssl V:0.5, 3100 xml/ processing DocBook XML │ │ │ │ │ │

* I:4 dsssl to various output │ │ │ │ │ │

formats with DSSSL │ │ │ │ │ │

├─────────────┼───────┼───────┼───────┼────────────────────────┤

utilities for DocBook │ │ │ │ │ │

files including │ │ │ │ │ │

docbook-utils V:0.2, 440 xml/ conversion to other │ │ │ │ │ │

Page 713: Referências Debian

* I:2 dsssl formats (HTML, RTF, PS, │ │ │ │ │ │

man, PDF) with docbook2*│ │ │ │ │ │

commands with DSSSL │ │ │ │ │ │

├─────────────┼───────┼───────┼───────┼────────────────────────┤

V:0.00, SGML/ converter from SGML and │ │ │ │ │ │

sgml2x * I:0.06 216 dsssl XML using DSSSL │ │ │ │ │ │

stylesheets │ │ │ │ │ │

└─────────────┴───────┴───────┴───────┴────────────────────────┘

Dica

GNOME's yelp is sometimes handy to read DocBook XML files

directly since it renders decently on X.

11.2.3. A extracção de dados de XML

You can extract HTML or XML data from other formats using

followings.

Tabela 11.10. Lista de ferramentas de extracção de dados de XML

┌─────────┬───────┬───────┬────────────────────┬───────────────┐

pacote popcon tamanho palavra chave descrição │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

document │ │ │ │ │ │

V:1.3, converter from │ │ │ │ │ │

Page 714: Referências Debian

wv * I:2 2116 MSWord→qualquer Microsoft Word │ │ │ │ │ │

to HTML, LaTeX,│ │ │ │ │ │

etc. │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

texi2html V:0.3, conversor de │ │ │ │ │ │

* I:2 2076 texi→html Texinfo para │ │ │ │ │ │

HTML │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

conversor de │ │ │ │ │ │

man2html V:0.2, manual │ │ │ │ │ │

* I:1.2 372 manpage→html (manpage) para │ │ │ │ │ │

HTML (suporte a│ │ │ │ │ │

CGI) │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

tex4ht * V:0.3, 924 tex↔html conversor entre│ │ │ │ │ │

I:2 (La)TeX e HTML │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

V:0.5, conversor de │ │ │ │ │ │

xlhtml * I:1.1 184 MSExcel→html .xls do MSExcel│ │ │ │ │ │

para HTML │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

V:0.5, conversor de │ │ │ │ │ │

ppthtml * I:1.1 120 MSPowerPoint→html MSPowerPoint │ │ │ │ │ │

para HTML │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

Page 715: Referências Debian

document │ │ │ │ │ │

unrtf * V:0.4, 224 rtf→html converter from │ │ │ │ │ │

I:0.9 RTF to HTML, │ │ │ │ │ │

etc │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

converter from │ │ │ │ │ │

info2www V:0.6, 156 info→html GNU info to │ │ │ │ │ │

* I:1.2 HTML (CGI │ │ │ │ │ │

support) │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

converter from │ │ │ │ │ │

ooo2dbk * V:0.03, 941 sxw→xml OpenOffice.org │ │ │ │ │ │

I:0.16 SXW documents │ │ │ │ │ │

to DocBook XML │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

Ficheiros do │ │ │ │ │ │

V:0.01, WordPerfect 5.0│ │ │ │ │ │

wp2x * I:0.07 240 WordPerfect→qualquer e 5.1 para TeX,│ │ │ │ │ │

LaTeX, troff, │ │ │ │ │ │

GML e HTML │ │ │ │ │ │

├─────────┼───────┼───────┼────────────────────┼───────────────┤

doclifter V:0.00, conversor de │ │ │ │ │ │

* I:0.03 424 troff→xml troff para │ │ │ │ │ │

DocBook XML │ │ │ │ │ │

└─────────┴───────┴───────┴────────────────────┴───────────────┘

Page 716: Referências Debian

For non-XML HTML files, you can convert them to XHTML which is

an instance of well formed XML. XHTML can be processed by XML

tools.

Tabela 11.11. Lista de ferramentas de impressão bonita de XML

┌─────────────┬──────┬───────┬──────────────┬──────────────────┐

pacote popcon tamanho palavra chave descrição │ │ │ │ │ │

├─────────────┼──────┼───────┼──────────────┼──────────────────┤

command line XML │ │ │ │ │ │

libxml2-utils V:3, 160 xml↔html↔xhtml tool with xmllint │ │ │ │ │ │

* I:49 (1) (syntax check,│ │ │ │ │ │

reformat, lint, …)│ │ │ │ │ │

├─────────────┼──────┼───────┼──────────────┼──────────────────┤

V:1.0, Verificador e │ │ │ │ │ │

tidy * I:9 108 xml↔html↔xhtml reformatador de │ │ │ │ │ │

sintaxe HTML │ │ │ │ │ │

└─────────────┴──────┴───────┴──────────────┴──────────────────┘

Once proper XML is generated, you can use XSLT technology to

extract data based on the mark-up context etc.

11.3. Dados imprimíveis

Printable data is expressed in the PostScript format on the

Page 717: Referências Debian

Debian system. Common Unix Printing System (CUPS) uses

Ghostscript as its rasterizer backend program for non-PostScript

printers.

11.3.1. Ghostscript

The core of printable data manipulation is the Ghostscript

PostScript (PS) interpreter which generates raster image.

The latest upstream Ghostscript from Artifex was re-licensed

from AFPL to GPL and merged all the latest ESP version changes

such as CUPS related ones at 8.60 release as unified release.

Tabela 11.12. List of Ghostscript PostScript interpreters

┌─────────────────┬───────┬───────┬────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

ghostscript * V:18, 6716 The GPL Ghostscript │ │ │ │ │

I:56 PostScript/PDF interpreter │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

V:13, GPL Ghostscript PostScript/ │ │ │ │ │

ghostscript-x * I:28 220 PDF interpreter - X display │ │ │ │ │

support │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

V:0.04, resource files for gs-cjk, │ │ │ │ │

gs-cjk-resource * I:0.4 4528 Ghostscript CJK-TrueType │ │ │ │ │

Page 718: Referências Debian

extension │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

cmap-adobe-cns1 * V:0.03, 1572 CMaps for Adobe-CNS1 (for │ │ │ │ │

I:0.3 traditional Chinese support)│ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

cmap-adobe-gb1 * V:0.03, 1552 CMaps for Adobe-GB1 (for │ │ │ │ │

I:0.3 simplified Chinese support) │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

cmap-adobe-japan1 V:0.08, 2428 CMaps for Adobe-Japan1 (for │ │ │ │ │

* I:0.7 Japanese standard support) │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

cmap-adobe-japan2 I:0.4 416 CMaps for Adobe-Japan2 (for │ │ │ │ │

* Japanese extra support) │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

cmap-adobe-korea1 V:0.01, 872 CMaps for Adobe-Korea1 (for │ │ │ │ │

* I:0.19 Korean support) │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

V:4, Biblioteca de renderização │ │ │ │ │

libpoppler5 * I:21 2368 de PDF baseada no │ │ │ │ │

visualizador de PDF xpdf │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

libpoppler-glib4 V:7, 504 PDF rendering library │ │ │ │ │

* I:19 (GLib-based shared library) │ │ │ │ │

├─────────────────┼───────┼───────┼────────────────────────────┤

Page 719: Referências Debian

CMaps for PDF rendering │ │ │ │ │

poppler-data * I:3 12232 library (for CJK support: │ │ │ │ │

Adobe-*) │ │ │ │ │

└─────────────────┴───────┴───────┴────────────────────────────┘

Dica

"gs -h" pode mostrar a configuração do Ghostscript.

11.3.2. Fundir dois ficheiros PS ou PDF

You can merge two PostScript (PS) or Portable Document Format

(PDF) files using gs(1) of Ghostscript.

$ gs -q -dNOPAUSE -dBATCH -sDEVICE=pswrite -sOutputFile=bla.ps -f foo1.ps foo2.ps

$ gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=bla.pdf -f foo1.pdf foo2.pdf

Nota

The PDF, which is widely used cross-platform printable data

format, is essentially the compressed PS format with few

additional features and extensions.

Dica

For command line, psmerge(1) and other commands from the psutils

Page 720: Referências Debian

package are useful for manipulating PostScript documents.

Commands in the pdfjam package work similarly for manipulating

PDF documents. pdftk(1) from the pdftk package is useful for

manipulating PDF documents, too.

11.3.3. Utilitários de dados imprimíveis

The following packages for the printable data utilities caught

my eyes.

Tabela 11.13. Lista de utilitários de dados imprimíveis

┌─────────────┬───────┬───────┬─────────────┬──────────────────┐

pacote popcon tamanho palavra chave descrição │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

PDF utilities: │ │ │ │ │ │

poppler-utils V:8, pdftops, pdfinfo, │ │ │ │ │ │

* I:49 536 pdf→ps,text,… pdfimages, │ │ │ │ │ │

pdftotext, │ │ │ │ │ │

pdffonts │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

V:3, PostScript │ │ │ │ │ │

psutils * I:21 380 ps→ps document │ │ │ │ │ │

conversion tools │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

V:1.2, create large │ │ │ │ │ │

poster * I:9 80 ps→ps posters out of │ │ │ │ │ │

Page 721: Referências Debian

PostScript pages │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

PDF utilities: │ │ │ │ │ │

V:0.9, pdftops, pdfinfo, │ │ │ │ │ │

xpdf-utils * I:4 76 pdf→ps,text,… pdfimages, │ │ │ │ │ │

pdftotext, │ │ │ │ │ │

pdffonts │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

convert ASCII text│ │ │ │ │ │

enscript * V:1.6, 2464 text→ps, to PostScript, │ │ │ │ │ │

I:14 html, rtf HTML, RTF or │ │ │ │ │ │

Pretty-Print │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

'Anything to │ │ │ │ │ │

a2ps * V:1.7, 4292 text→ps PostScript' │ │ │ │ │ │

I:8 converter and │ │ │ │ │ │

pretty-printer │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

V:1.0, PDF document │ │ │ │ │ │

pdftk * I:5 200 pdf→pdf conversion tool: │ │ │ │ │ │

pdftk │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

mpage * V:0.18, 224 text,ps→ps print multiple │ │ │ │ │ │

I:1.5 pages per sheet │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

Page 722: Referências Debian

html2ps * V:0.2, 260 html→ps conversor de HTML │ │ │ │ │ │

I:1.7 para PostScript │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

PDF document │ │ │ │ │ │

pdfjam * V:0.2, 228 pdf→pdf conversion tools: │ │ │ │ │ │

I:1.8 pdf90, pdfjoin, │ │ │ │ │ │

and pdfnup │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

gnuhtml2latex V:0.07, 60 html→latex conversor de html │ │ │ │ │ │

* I:0.6 para latex │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

convert documents │ │ │ │ │ │

latex2rtf * V:0.14, 508 latex→rtf from LaTeX to RTF │ │ │ │ │ │

I:1.0 which can be read │ │ │ │ │ │

by MS Word │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

converter from │ │ │ │ │ │

ps2eps * V:1.3, 116 ps→eps PostScript to EPS │ │ │ │ │ │

I:12 (Encapsulated │ │ │ │ │ │

PostScript) │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

Text to PostScript│ │ │ │ │ │

e2ps * V:0.01, 188 text→ps converter with │ │ │ │ │ │

I:0.10 Japanese encoding │ │ │ │ │ │

support │ │ │ │ │ │

Page 723: Referências Debian

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

impose+ * V:0.03, 180 ps→ps PostScript │ │ │ │ │ │

I:0.2 utilities │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

pretty print many │ │ │ │ │ │

source codes (C, │ │ │ │ │ │

V:0.02, C++, Java, Pascal,│ │ │ │ │ │

trueprint * I:0.13 188 text→ps Perl, Pike, Sh, │ │ │ │ │ │

and Verilog) to │ │ │ │ │ │

PostScript. (C │ │ │ │ │ │

language) │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

V:0.10, converter from PDF│ │ │ │ │ │

pdf2svg * I:0.5 60 ps→svg to Scalable vector│ │ │ │ │ │

graphics format │ │ │ │ │ │

├─────────────┼───────┼───────┼─────────────┼──────────────────┤

V:0.02, converter from PDF│ │ │ │ │ │

pdftoipe * I:0.16 88 ps→ipe to IPE's XML │ │ │ │ │ │

format │ │ │ │ │ │

└─────────────┴───────┴───────┴─────────────┴──────────────────┘

11.3.4. Imprimir com o CUPS

Both lp(1) and lpr(1) commands offered by Common Unix Printing

System (CUPS) provides options for customized printing the

Page 724: Referências Debian

printable data.

You can print 3 copies of a file collated using one of the

following commands.

$ lp -n 3 -o Collate=True nome_do_ficheiro

$ lpr -#3 -o Collate=True nome_do_ficheiro

You can further customize printer operation by using printer

option such as "-o number-up=2", "-o page-set=even", "-o

page-set=odd", "-o scaling=200", "-o natural-scaling=200", etc.,

documented at Command-Line Printing and Options.

11.4. Type setting

The Unix troff program originally developed by AT&T can be used

for simple typesetting. It is usually used to create manpages.

TeX created by Donald Knuth is very powerful type setting tool

and is the de facto standard. LaTeX originally written by Leslie

Lamport enables a high-level access to the power of TeX.

Tabela 11.14. List of type setting tools

┌───────┬──────┬───────┬────────┬──────────────────────────────┐

pacote popcon tamanho palavra descrição │ │ │ │ │ │

chave │ │ │ │ │ │

Page 725: Referências Debian

├───────┼──────┼───────┼────────┼──────────────────────────────┤

texlive V:0.5, 124 (La)TeX TeX system for typesetting, │ │ │ │ │ │

* I:9 previewing and printing │ │ │ │ │ │

├───────┼──────┼───────┼────────┼──────────────────────────────┤

groff * V:0.9, 9116 troff O sistema de formato de texto │ │ │ │ │ │

I:7 troff do GNU │ │ │ │ │ │

└───────┴──────┴───────┴────────┴──────────────────────────────┘

11.4.1. roff typesetting

Traditionally, roff is the main Unix text processing system. See

roff(7), groff(7), groff(1), grotty(1), troff(1), groff_mdoc(7),

groff_man(7), groff_ms(7), groff_me(7), groff_mm(7), and "info

groff".

You can read or print a good tutorial and reference on "-me"

macro in "/usr/share/doc/groff/" by installing the groff

package.

Dica

"groff -Tascii -me -" produces plain text output with ANSI

escape code. If you wish to get manpage like output with many "^

H" and "_", use "GROFF_NO_SGR=1 groff -Tascii -me -" instead.

Dica

Page 726: Referências Debian

To remove "^H" and "_" from a text file generated by groff,

filter it by "col -b -x".

11.4.2. TeX/LaTeX

The TeX Live software distribution offers a complete TeX system.

The texlive metapackage provides a decent selection of the TeX

Live packages which should suffice for the most common tasks.

There are many references available for TeX and LaTeX.

The teTeX HOWTO: The Linux-teTeX Local Guide●

tex(1)●

latex(1)●

"The TeXbook", por Donald E. Knuth, (Addison-Wesley)●

"LaTeX - A Document Preparation System", por Leslie Lamport,●

(Addison-Wesley)

"The LaTeX Companion", por Goossens, Mittelbach, Samarin,●

(Addison-Wesley)

This is the most powerful typesetting environment. Many SGML

processors use this as their back end text processor. Lyx

provided by the lyx package and GNU TeXmacs provided by the

texmacs package offer nice WYSIWYG editing environment for LaTeX

while many use Emacs and Vim as the choice for the source

editor.

Existem muitos recursos online disponíveis.

Page 727: Referências Debian

The TEX Live Guide - TEX Live 2007 ("/usr/share/doc/●

texlive-doc-base/english/texlive-en/live.html")

(texlive-doc-base package)

Um Guia Simples para o Latex/Lyx●

Processamento de Texto Usando o LaTeX●

Guia do Utilizador Local para o teTeX/LaTeX●

When documents become bigger, sometimes TeX may cause errors.

You must increase pool size in "/etc/texmf/texmf.cnf" (or more

appropriately edit "/etc/texmf/texmf.d/95NonPath" and run

update-texmf(8)) to fix this.

Nota

The TeX source of "The TeXbook" is available at http://

tug.ctan.org/tex-archive/systems/knuth/dist/tex/texbook.tex.

This file contains most of the required macros. I heard that you

can process this document with tex(1) after commenting lines 7

to 10 and adding "\input manmac \proofmodefalse". It's strongly

recommended to buy this book (and all other books from Donald E.

Knuth) instead of using the online version but the source is a

great example of TeX input!

11.4.3. Impressão bonita de um manual

Você consegue uma impressão bonita dum manual em PostScript com

um dos seguintes comandos.

Page 728: Referências Debian

$ man -Tps qualquer_manual | lpr

$ man -Tps qualquer_manual | mpage -2 | lpr

O segundo exemplo imprime duas páginas em cada folha.

11.4.4. Criar um manual

Apesar de escrever um manual (manpage) no formato troff simples

ser possível, existem alguns programas que ajudam a criá-lo.

Tabela 11.15. Lista de pacotes para ajudar a criar o manual

(manpage)

┌──────────────┬───────┬───────┬─────────────┬─────────────────┐

pacote popcon tamanho palavra chave descrição │ │ │ │ │ │

├──────────────┼───────┼───────┼─────────────┼─────────────────┤

docbook-to-man V:0.3, conversor de │ │ │ │ │ │

* I:2 240 SGML→manpage DocBook SGML para│ │ │ │ │ │

macros roff man │ │ │ │ │ │

├──────────────┼───────┼───────┼─────────────┼─────────────────┤

geração │ │ │ │ │ │

help2man * V:0.13, 376 texto→manpage automática de │ │ │ │ │ │

I:1.1 manual a partir │ │ │ │ │ │

do --help │ │ │ │ │ │

├──────────────┼───────┼───────┼─────────────┼─────────────────┤

Page 729: Referências Debian

V:0.02, conversor de info│ │ │ │ │ │

info2man * I:0.15 204 info→manpage do GNU para POD │ │ │ │ │ │

ou páginas man │ │ │ │ │ │

├──────────────┼───────┼───────┼─────────────┼─────────────────┤

converte texto │ │ │ │ │ │

txt2man * V:0.02, 88 texto→manpage ASCII simples │ │ │ │ │ │

I:0.2 para o formato de│ │ │ │ │ │

página man │ │ │ │ │ │

└──────────────┴───────┴───────┴─────────────┴─────────────────┘

11.5. A conversão de dados de mail

Os seguintes pacotes para conversão de dados de mail chamaram a

minha atenção.

Tabela 11.16. Lista de pacotes para ajudar na conversão de dados

de mail

┌─────────┬───────┬───────┬───────┬────────────────────────────┐

pacote popcon tamanho palavra descrição │ │ │ │ │ │

chave │ │ │ │ │ │

├─────────┼───────┼───────┼───────┼────────────────────────────┤

sharutils V:2, 904 mail shar(1), unshar(1), uuencode│ │ │ │ │ │

* I:32 (1), uudecode(1) │ │ │ │ │ │

├─────────┼───────┼───────┼───────┼────────────────────────────┤

Page 730: Referências Debian

V:1.5, codificar e descodificar │ │ │ │ │ │

mpack * I:23 84 MIME mensagens MIME: mpack(1) e │ │ │ │ │ │

munpack(1) │ │ │ │ │ │

├─────────┼───────┼───────┼───────┼────────────────────────────┤

descompactar anexos MIME do │ │ │ │ │ │

tnef * V:0.8, 164 ms-tnef tipo "application/ms-tnef" o│ │ │ │ │ │

I:1.5 qual é um formato apenas da │ │ │ │ │ │

Microsoft │ │ │ │ │ │

├─────────┼───────┼───────┼───────┼────────────────────────────┤

encoder and decoder for the │ │ │ │ │ │

uudeview V:0.17, 132 mail following formats: uuencode,│ │ │ │ │ │

* I:1.6 xxencode, BASE64, quoted │ │ │ │ │ │

printable, and BinHex │ │ │ │ │ │

├─────────┼───────┼───────┼───────┼────────────────────────────┤

V:0.04, converter ficheiros PST do │ │ │ │ │ │

readpst * I:0.3 228 PST Outlook da Microsoft para │ │ │ │ │ │

formato mbox │ │ │ │ │ │

└─────────┴───────┴───────┴───────┴────────────────────────────┘

Dica

The Internet Message Access Protocol version 4 (IMAP4) server

(see Secção 6.7, “Servidor POP3/IMAP4”) may be used to move

mails out from proprietary mail systems if the mail client

software can be configured to use IMAP4 server too.

Page 731: Referências Debian

11.5.1. Noções básicas de dados de mail

Mail (SMTP) data should be limited to 7 bit. So binary data and

8 bit text data are encoded into 7 bit format with the

Multipurpose Internet Mail Extensions (MIME) and the selection

of the charset (see Secção 8.3.1, “Bases de codificação”).

The standard mail storage format is mbox formatted according to

RFC2822 (updated RFC822). See mbox(5) (provided by the mutt

package).

For European languages, "Content-Transfer-Encoding:

quoted-printable" with the ISO-8859-1 charset is usually used

for mail since there are not much 8 bit characters. If European

text is encoded in UTF-8, "Content-Transfer-Encoding:

quoted-printable" is likely to be used since it is mostly 7 bit

data.

For Japanese, traditionally "Content-Type: text/plain; charset=

ISO-2022-JP" is usually used for mail to keep text in 7 bits.

But older Microsoft systems may send mail data in Shift-JIS

without proper declaration. If Japanese text is encoded in

UTF-8, Base64 is likely to be used since it contains many 8 bit

data. The situation of other Asian languages is similar.

Nota

If your non-Unix mail data is accessible by a non-Debian client

software which can talk to the IMAP4 server, you may be able to

Page 732: Referências Debian

move them out by running your own IMAP4 server (see Secção 6.7,

“Servidor POP3/IMAP4”).

Nota

If you use other mail storage formats, moving them to mbox

format is the good first step. The versatile client program such

as mutt(1) may be handy for this.

You can split mailbox contents to each message using procmail(1)

and formail(1).

Each mail message can be unpacked using munpack(1) from the

mpack package (or other specialized tools) to obtain the MIME

encoded contents.

11.6. Ferramentas de dados gráficos

Os seguintes pacotes para conversão de dados gráficos, edição e

ferramentas de organização chamaram a minha atenção.

Tabela 11.17. Lista de ferramentas de dados gráficos

┌────────────────────────┬───────┬───────┬─────────────────┬───────────────┐

pacote popcon tamanho palavra chave descrição │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

V:12, GNU Image │ │ │ │ │ │

gimp * I:44 13560 imagem(bitmap) Manipulation │ │ │ │ │ │

Page 733: Referências Debian

Program │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

V:13, programas de │ │ │ │ │ │

imagemagick * I:35 268 imagem(bitmap) manipulação de │ │ │ │ │ │

imagens │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

programas de │ │ │ │ │ │

V:1.6, manipulação de │ │ │ │ │ │

graphicsmagick * I:3 4532 imagem(bitmap) imagens │ │ │ │ │ │

(parentes do │ │ │ │ │ │

imagemagick) │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

Frontend X11 │ │ │ │ │ │

V:5, baseado em GTK+│ │ │ │ │ │

xsane * I:36 748 imagem(bitmap) para o SANE │ │ │ │ │ │

(Scanner Access│ │ │ │ │ │

Now Easy) │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

V:4, ferramentas de │ │ │ │ │ │

netpbm * I:29 4612 imagem(bitmap) conversão de │ │ │ │ │ │

gráficos │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

convert MS │ │ │ │ │ │

Windows icons │ │ │ │ │ │

icoutils * V:0.3, 200 png↔ico(bitmap) and cursors to │ │ │ │ │ │

I:1.3 and from PNG │ │ │ │ │ │

Page 734: Referências Debian

formats ( │ │ │ │ │ │

favicon.ico) │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

scribus * V:0.5, 26888 ps/pdf/SVG/… editor de DTP │ │ │ │ │ │

I:3 do Scribus │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

suite de │ │ │ │ │ │

openoffice.org-draw * V:18, 10720 imagem(vector) escritório do │ │ │ │ │ │

I:40 OpenOffice.org │ │ │ │ │ │

- desenho │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

editor de SVG │ │ │ │ │ │

inkscape * V:15, 87436 imagem(vector) (Scalable │ │ │ │ │ │

I:32 Vector │ │ │ │ │ │

Graphics) │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

V:1.4, editor de │ │ │ │ │ │

dia-gnome * I:2 576 imagem(vector) diagramas │ │ │ │ │ │

(GNOME) │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

dia * V:3, 572 imagem(vector) editor de │ │ │ │ │ │

I:5 diagramas (Gtk)│ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

facility for │ │ │ │ │ │

V:2, Interactive │ │ │ │ │ │

Page 735: Referências Debian

xfig * I:4 1676 imagem(vector) Generation of │ │ │ │ │ │

figures under │ │ │ │ │ │

X11 │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

conversor de │ │ │ │ │ │

ficheiro │ │ │ │ │ │

V:1.9, ps/pdf→imagem PostScript e │ │ │ │ │ │

pstoedit * I:16 708 (vector) PDF para │ │ │ │ │ │

gráficos │ │ │ │ │ │

vectoriais │ │ │ │ │ │

editáveis (SVG)│ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

Windows │ │ │ │ │ │

metafile │ │ │ │ │ │

libwmf-bin * V:1.4, 68 Windows/imagem (vector graphic│ │ │ │ │ │

I:13 (vector) data) │ │ │ │ │ │

conversion │ │ │ │ │ │

tools │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

convert XFig │ │ │ │ │ │

fig2sxd * V:0.03, 200 fig→sxd(vector) files to │ │ │ │ │ │

I:0.2 OpenOffice.org │ │ │ │ │ │

Draw format │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

post-processing│ │ │ │ │ │

unpaper * V:0.2, 736 imagem→imagem tool for │ │ │ │ │ │

I:1.7 scanned pages │ │ │ │ │ │

Page 736: Referências Debian

for OCR │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

free OCR │ │ │ │ │ │

V:0.7, software based │ │ │ │ │ │

tesseract-ocr * I:3 3196 imagem→texto on the HP's │ │ │ │ │ │

commercial OCR │ │ │ │ │ │

engine │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

OCR engine │ │ │ │ │ │

data: │ │ │ │ │ │

tesseract-ocr-eng * V:0.2, 1752 imagem→texto tesseract-ocr │ │ │ │ │ │

I:2 language files │ │ │ │ │ │

for English │ │ │ │ │ │

text │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

gocr * V:0.8, 492 imagem→texto software de OCR│ │ │ │ │ │

I:5 livre │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

ocrad * V:0.4, 364 imagem→texto software de OCR│ │ │ │ │ │

I:4 livre │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

manipular │ │ │ │ │ │

ficheiros de │ │ │ │ │ │

gtkam * V:0.3, 1100 imagem(Exif) fotos de │ │ │ │ │ │

I:1.7 cameras │ │ │ │ │ │

digitais │ │ │ │ │ │

Page 737: Referências Debian

(GNOME) - GUI │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

manipular │ │ │ │ │ │

ficheiros de │ │ │ │ │ │

V:0.3, fotos de │ │ │ │ │ │

gphoto2 * I:2 1008 imagem(Exif) cameras │ │ │ │ │ │

digitais │ │ │ │ │ │

(GNOME) - linha│ │ │ │ │ │

de comandos │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

manipular │ │ │ │ │ │

V:0.7, ficheiros de │ │ │ │ │ │

kamera * I:13 312 imagem(Exif) fotos de │ │ │ │ │ │

cameras │ │ │ │ │ │

digitais (KDE) │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

manipulate the │ │ │ │ │ │

non-image part │ │ │ │ │ │

jhead * V:0.5, 132 imagem(Exif) of Exif │ │ │ │ │ │

I:3 compliant JPEG │ │ │ │ │ │

(digital camera│ │ │ │ │ │

photo) files │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

utilitário de │ │ │ │ │ │

linha de │ │ │ │ │ │

V:0.2, comandos para │ │ │ │ │ │

exif * I:1.7 184 imagem(Exif) mostrar │ │ │ │ │ │

Page 738: Referências Debian

informação EXIF│ │ │ │ │ │

nos ficheiros │ │ │ │ │ │

JPEG │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

utility to read│ │ │ │ │ │

V:0.14, Exif tags from │ │ │ │ │ │

exiftags * I:0.9 248 imagem(Exif) a digital │ │ │ │ │ │

camera JPEG │ │ │ │ │ │

file │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

transformar │ │ │ │ │ │

exiftran * V:0.4, 56 imagem(Exif) imagens jpeg de│ │ │ │ │ │

I:3 cameras │ │ │ │ │ │

digitais │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

V:0.08, ler metadados │ │ │ │ │ │

exifprobe * I:0.5 484 imagem(Exif) de imagens │ │ │ │ │ │

digitais │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

V:0.9, decode raw │ │ │ │ │ │

dcraw * I:5 444 imagem(Raw)→ppm digital camera │ │ │ │ │ │

images │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

encontra │ │ │ │ │ │

V:0.06, imagens │ │ │ │ │ │

findimagedupes * I:0.4 140 image→fingerprint visualmente │ │ │ │ │ │

Page 739: Referências Debian

semelhantes ou │ │ │ │ │ │

duplicadas │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

merge images to│ │ │ │ │ │

ale * V:0.02, 768 imagem→imagem increase │ │ │ │ │ │

I:0.17 fidelity or │ │ │ │ │ │

create mosaics │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

V:0.03, generate static│ │ │ │ │ │

imageindex * I:0.2 192 imagem(Exif)→html HTML galleries │ │ │ │ │ │

from images │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

aplicação de │ │ │ │ │ │

f-spot * V:0.5, 9488 imagem(Exif) gestão de fotos│ │ │ │ │ │

I:1.8 pessoais │ │ │ │ │ │

(GNOME) │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

gera álbuns de │ │ │ │ │ │

V:0.02, fotos estáticos│ │ │ │ │ │

bins * I:0.15 2008 imagem(Exif)→html em HTML usando │ │ │ │ │ │

XML e etiquetas│ │ │ │ │ │

EXIF │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

gera álbuns de │ │ │ │ │ │

V:0.2, fotos │ │ │ │ │ │

gallery2 * I:0.4 62548 imagem(Exif)→html exploráveis em │ │ │ │ │ │

Page 740: Referências Debian

HTML com │ │ │ │ │ │

miniaturas │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

V:0.02, ferramenta de │ │ │ │ │ │

outguess * I:0.14 252 jpeg,png Esteganografia │ │ │ │ │ │

universal │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

qcad * V:1.5, 3944 DXF editor de dados│ │ │ │ │ │

I:2 CAD (KDE) │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

editor de │ │ │ │ │ │

blender * V:0.5, 28336 blend, TIFF, conteúdos 3D │ │ │ │ │ │

I:3 VRML, … para animação e│ │ │ │ │ │

etc │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

editor de │ │ │ │ │ │

mm3d * V:0.04, 4536 ms3d, obj, dxf, … modelos 3D │ │ │ │ │ │

I:0.3 baseado em │ │ │ │ │ │

OpenGL │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

open-font-design-toolkit meta pacote │ │ │ │ │ │

* I:0.03 36 ttf, ps, … para desenho de│ │ │ │ │ │

font aberta │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

editor de tipo │ │ │ │ │ │

Page 741: Referências Debian

V:0.2, de letra para │ │ │ │ │ │

fontforge * I:1.7 6612 ttf, ps, … fonts PS, │ │ │ │ │ │

TrueType e │ │ │ │ │ │

OpenType │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

program for │ │ │ │ │ │

xgridfit * V:0.01, 1060 ttf gridfitting and│ │ │ │ │ │

I:0.07 hinting │ │ │ │ │ │

TrueType fonts │ │ │ │ │ │

├────────────────────────┼───────┼───────┼─────────────────┼───────────────┤

gbdfed * V:0.01, 496 bdf editor for BDF │ │ │ │ │ │

I:0.11 fonts │ │ │ │ │ │

└────────────────────────┴───────┴───────┴─────────────────┴───────────────┘

Dica

Search more image tools using regex "~Gworks-with::image" in

aptitude(8) (see Secção 2.2.6, “Opções do método de pesquisa com

o aptitude”).

Although GUI programs such as gimp(1) are very powerful, command

line tools such as imagemagick(1) are quite useful for

automating image manipulation with the script.

The de facto image file format of the digital camera is the

Exchangeable Image File Format (EXIF) which is the JPEG image

Page 742: Referências Debian

file format with additional metadata tags. It can hold

information such as date, time, and camera settings.

The Lempel-Ziv-Welch (LZW) lossless data compression patent has

been expired. Graphics Interchange Format (GIF) utilities which

use the LZW compression method are now freely available on the

Debian system.

Dica

Any digital camera or scanner with removable recording media

works with Linux through USB storage readers since it follows

the Design rule for Camera Filesystem and uses FAT filesystem.

See Secção 10.1.10, “Dispositivo de armazenamento amovível”.

11.7. Conversão de dados variados

There are many other programs for converting data. Following

packages caught my eyes using regex "~Guse::converting" in

aptitude(8) (see Secção 2.2.6, “Opções do método de pesquisa com

o aptitude”).

Tabela 11.18. Lista de ferramentas de conversão de dados

variados

┌─────────┬───────┬───────┬─────────┬──────────────────────────┐

pacote popcon tamanho palavra descrição │ │ │ │ │ │

chave │ │ │ │ │ │

Page 743: Referências Debian

├─────────┼───────┼───────┼─────────┼──────────────────────────┤

V:1.2, rpm/ converter for the foreign │ │ │ │ │ │

alien * I:11 244 tgz→deb package into the Debian │ │ │ │ │ │

package │ │ │ │ │ │

├─────────┼───────┼───────┼─────────┼──────────────────────────┤

converter from "Electric │ │ │ │ │ │

freepwing V:0.00, Book" (popular in Japan) │ │ │ │ │ │

* I:0.03 568 EB→EPWING to a single JIS X 4081 │ │ │ │ │ │

format (a subset of the │ │ │ │ │ │

EPWING V1) │ │ │ │ │ │

└─────────┴───────┴───────┴─────────┴──────────────────────────┘

You can also extract data from RPM format with the following.

$ rpm2cpio file.src.rpm | cpio --extract

Capítulo 12. Programação

I provide some pointers for people to learn programming on the

Debian system enough to trace the packaged source code. Here are

notable packages and corresponding documentation packages for

programing.

Tabela 12.1. Lista de pacotes para ajudar a programar

┌───────────────┬───────┬───────┬──────────────────────────────┐

Page 744: Referências Debian

pacote popcon tamanho documentação │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:4, "info autoconf" │ │ │ │ │

autoconf * I:25 2256 disponibilizado por │ │ │ │ │

autoconf-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:3, "info automake" │ │ │ │ │

automake * I:21 1812 disponibilizado por │ │ │ │ │

automake1.10-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

bash * V:91, 3536 "info bash" disponibilizado │ │ │ │ │

I:99 por bash-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

bison * V:2, 1504 "info bison" disponibilizado │ │ │ │ │

I:15 por bison-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

cpp * V:38, 32 "info cpp" disponibilizado por│ │ │ │ │

I:82 cpp-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

ddd * V:0.3, 3852 "info ddd" disponibilizado por│ │ │ │ │

I:2 ddd-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

exuberant-ctags V:1.2, 284 exuberant-ctags(1) │ │ │ │ │

* I:5 │ │ │ │ │

Page 745: Referências Debian

├───────────────┼───────┼───────┼──────────────────────────────┤

flex * V:2, 1352 "info flex" disponibilizado │ │ │ │ │

I:15 por flex-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

gawk * V:28, 2172 "info gawk" disponibilizado │ │ │ │ │

I:32 por gawk-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

gcc * V:17, 28 "info gcc" disponibilizado por│ │ │ │ │

I:67 gcc-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

gdb * V:4, 4812 "info gdb" disponibilizado por│ │ │ │ │

I:22 gdb-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

gettext * V:8, 7272 "info gettext" disponibilizado│ │ │ │ │

I:46 por gettext-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:0.9, "info gfortran" │ │ │ │ │

gfortran * I:6 8 disponibilizado por │ │ │ │ │

gfortran-doc (Fortran 95) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

gpc * V:0.07, 8 "info gpc" disponibilizado por│ │ │ │ │

I:0.5 gpc-doc (Pascal) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

fpc * I:0.4 40 fpc(1) e html por fp-docs │ │ │ │ │

Page 746: Referências Debian

(Pascal) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

glade * V:0.3, 1652 ajuda disponibilizada via menu│ │ │ │ │

I:2 (UI Builder) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

glade-gnome * V:0.09, 508 ajuda disponibilizada via menu│ │ │ │ │

I:1.2 (UI Builder) │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:97, "info libc" disponibilizado │ │ │ │ │

libc6 * I:99 10012 por glibc-doc e │ │ │ │ │

glibc-doc-reference │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

make * V:21, 1220 "info make" disponibilizado │ │ │ │ │

I:72 por make-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

xutils-dev * V:1.7, 1728 imake(1), xmkmf(1), etc. │ │ │ │ │

I:15 │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

mawk * V:66, 244 mawk(1) │ │ │ │ │

I:99 │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

V:88, perl(1) e páginas html │ │ │ │ │

perl * I:99 18528 disponibilizadas por perl-doc │ │ │ │ │

e perl-doc-html │ │ │ │ │

Page 747: Referências Debian

├───────────────┼───────┼───────┼──────────────────────────────┤

V:62, python(1) e páginas html │ │ │ │ │

python * I:97 736 disponibilizadas por │ │ │ │ │

python-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

tcl8.4 * V:8, 3332 tcl(3) and detail manual pages│ │ │ │ │

I:46 provided by tcl8.4-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

tk8.4 * V:5, 2712 tk(3) and detail manual pages │ │ │ │ │

I:34 provided by tk8.4-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

ruby * V:9, 120 ruby(1) and interactive │ │ │ │ │

I:24 reference provided by ri │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

vim * V:15, 1792 help(F1) menu disponibilizado │ │ │ │ │

I:33 por vim-doc │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

susv2 * I:0.03 48 fetch "The Single Unix │ │ │ │ │

Specifications v2" │ │ │ │ │

├───────────────┼───────┼───────┼──────────────────────────────┤

susv3 * I:0.07 48 fetch "The Single Unix │ │ │ │ │

Specifications v3" │ │ │ │ │

└───────────────┴───────┴───────┴──────────────────────────────┘

Page 748: Referências Debian

Online references are available by typing "man name" after

installing manpages and manpages-dev packages. Online references

for the GNU tools are available by typing "info program_name"

after installing the pertinent documentation packages. You may

need to include the contrib and non-free archives in addition to

the main archive since some GFDL documentations are not

considered to be DSFG compliant.

Atenção

Do not use "test" as the name of an executable test file. "test"

is a shell builtin.

Cuidado

You should install software programs directly compiled from

source into "/usr/local" or "/opt" to avoid collision with

system programs.

Dica

Code examples of creating "Song 99 Bottles of Beer" should give

you good idea of practically all the programming languages.

12.1. O script shell

The shell script is a text file with the execution bit set and

contains the commands in the following format.

Page 749: Referências Debian

#!/bin/sh

... linhas de comando

The first line specifies the shell interpreter which read and

execute this file contents.

Reading shell scripts is the best way to understand how a

Unix-like system works. Here, I give some pointers and reminders

for shell programming. See "Shell Mistakes" (http://

www.greenend.org.uk/rjk/2001/04/shell.html) to learn from

mistakes.

Unlike shell interactive mode (see Secção 1.5, “O simples

comando de shell” and Secção 1.6, “Processamento de texto estilo

Unix”), shell scripts frequently use parameters, conditionals,

and loops.

12.1.1. Compatibilidade da shell do POSIX

Many system scripts may be interpreted by any one of POSIX

shells (see Tabela 1.13, “Lista de programas da shell”). The

default shell for the system is "/bin/sh" which is a symlink

pointing to the actual program.

bash(1) para lenny ou mais antigo●

dash(1) para squeeze ou mais recente●

Avoid writing a shell script with bashisms or zshisms to make it

Page 750: Referências Debian

portable among all POSIX shells. You can check it using

checkbashisms(1).

Tabela 12.2. Lista dos bashisms típicos

┌──────────────────────────────┬───────────────────────────────┐

Bom: POSIX Evitar: bashism │ │ │

├──────────────────────────────┼───────────────────────────────┤

if [ "$foo" = "$bar" ] ; then if [ "$foo" == "$bar" ] ; then │ │ │

… … │ │ │

├──────────────────────────────┼───────────────────────────────┤

diff -u file.c.orig file.c diff -u file.c{.orig,} │ │ │

├──────────────────────────────┼───────────────────────────────┤

mkdir /foobar /foobaz mkdir /foo{bar,baz} │ │ │

├──────────────────────────────┼───────────────────────────────┤

funcname() { … } function funcname() { … } │ │ │

├──────────────────────────────┼───────────────────────────────┤

formato octal: "\377" formato hexadecimal: "\xff" │ │ │

└──────────────────────────────┴───────────────────────────────┘

The "echo" command must be used with following cares since its

implementation differs among shell builtin and external

commands.

Page 751: Referências Debian

Avoid using command option "-e" and "-E".●

Evite usar quaisquer opções de comando excepto "-n".●

Avoid using escape sequences in the string since their●

handling varies.

Nota

Although "-n" option is not really POSIX syntax, it is generally

accepted.

Dica

Use the "printf" command instead of the "echo" command if you

need to embed escape sequences in the output string.

12.1.2. Parâmetros da shell

Parâmetros de shell especiais são frequentemente usados no

script shell.

Tabela 12.3. Lista de parâmetros da shel

┌──────────────────┬───────────────────────────────────────────┐

parâmetro da shell valor │ │ │

├──────────────────┼───────────────────────────────────────────┤

$0 nome da shell ou script de shell │ │ │

├──────────────────┼───────────────────────────────────────────┤

Page 752: Referências Debian

$1 primeiro(1) argumento shell │ │ │

├──────────────────┼───────────────────────────────────────────┤

$9 nono(9) argumento shell │ │ │

├──────────────────┼───────────────────────────────────────────┤

$# número de parâmetros de posição │ │ │

├──────────────────┼───────────────────────────────────────────┤

"$*" "$1 $2 $3 $4 … " │ │ │

├──────────────────┼───────────────────────────────────────────┤

"$@" "$1" "$2" "$3" "$4" … │ │ │

├──────────────────┼───────────────────────────────────────────┤

$? estado de saída do comando mais recente │ │ │

├──────────────────┼───────────────────────────────────────────┤

$$ PID deste script shell │ │ │

├──────────────────┼───────────────────────────────────────────┤

$! PID of most recently started background job│ │ │

└──────────────────┴───────────────────────────────────────────┘

Basic parameter expansions to remember are followings.

Tabela 12.4. Lista de expansões de parâmetros de shell

┌──────────────────┬────────────────┬──────────────────────────┐

formato da valor se var valor se var não estiver │ │ │ │

Page 753: Referências Debian

expressão do estiver definido definido │ │ │ │

parâmetro │ │ │ │

├──────────────────┼────────────────┼──────────────────────────┤

${var:-string} "$var" "string" │ │ │ │

├──────────────────┼────────────────┼──────────────────────────┤

${var:+string} "string" "null" │ │ │ │

├──────────────────┼────────────────┼──────────────────────────┤

${var:=string} "$var" "string" (e corra "var= │ │ │ │

string") │ │ │ │

├──────────────────┼────────────────┼──────────────────────────┤

${var:?string} "$var" echo "string" para stderr │ │ │ │

(e termina com erro) │ │ │ │

└──────────────────┴────────────────┴──────────────────────────┘

Aqui, os o caractere dois pontos ":" em todas estas operações é

na realidade opcional.

with ":" = operator test for exist and not null●

without ":" = operator test for exist only●

Tabela 12.5. Lista de substituições de parâmetros de shell chave

┌────────────────────────────────┬─────────────────────────────┐

formato de substituição de resultado │ │ │

Page 754: Referências Debian

parâmetro │ │ │

├────────────────────────────────┼─────────────────────────────┤

${var%suffix} remover o padrão de sufixo │ │ │

menor │ │ │

├────────────────────────────────┼─────────────────────────────┤

${var%%suffix} remover o padrão de sufixo │ │ │

maior │ │ │

├────────────────────────────────┼─────────────────────────────┤

${var#prefix} remover o padrão de prefixo │ │ │

menor │ │ │

├────────────────────────────────┼─────────────────────────────┤

${var##prefix} remover o padrão de prefixo │ │ │

maior │ │ │

└────────────────────────────────┴─────────────────────────────┘

12.1.3. Condicionais da shell

Each command returns an exit status which can be used for

conditional expressions.

Sucesso: 0 ("True")●

Erro: não 0 ("False")●

Nota

Page 755: Referências Debian

"0" in the shell conditional context means "True", while "0" in

the C conditional context means "False".

Nota

"[" is the equivalent of the test command, which evaluates its

arguments up to "]" as a conditional expression.

Basic conditional idioms to remember are followings.

"<command> && <if_success_run_this_command_too> || true"●

"<command> || <if_not_success_run_this_command_too> || true"●

A multi-line script snippet as the following●

if [ <conditional_expression> ]; then

<if_success_run_this_command>

else

<if_not_success_run_this_command>

fi

Here trailing "|| true" was needed to ensure this shell script

does not exit at this line accidentally when shell is invoked

with "-e" flag.

Tabela 12.6. Lista de operadores de comparação de ficheiros na

expressão condicional

┌────────────────┬─────────────────────────────────────────────┐

Page 756: Referências Debian

equação condição para retornar o verdadeiro lógico │ │ │

├────────────────┼─────────────────────────────────────────────┤

-e <ficheiro> <ficheiro> existe │ │ │

├────────────────┼─────────────────────────────────────────────┤

-d <ficheiro> <ficheiro> existe e é um directório │ │ │

├────────────────┼─────────────────────────────────────────────┤

-f <ficheiro> <ficheiro> existe e é um ficheiro normal │ │ │

├────────────────┼─────────────────────────────────────────────┤

-w <ficheiro> <ficheiro> existe e pode-se escrever nele │ │ │

├────────────────┼─────────────────────────────────────────────┤

-x <ficheiro> <ficheiro> existe e é executável │ │ │

├────────────────┼─────────────────────────────────────────────┤

<ficheiro1> -nt <ficheiro1> é mais recente que <ficheiro2> │ │ │

<ficheiro2> (modificação) │ │ │

├────────────────┼─────────────────────────────────────────────┤

<ficheiro1> -ot <ficheiro1> é mais antigo que <ficheiro2> │ │ │

<ficheiro2> (modificação) │ │ │

├────────────────┼─────────────────────────────────────────────┤

<ficheiro1> -ef <ficheiro1> e <ficheiro2> estão no mesmo │ │ │

<ficheiro2> dispositivo e no mesmo número de inode │ │ │

└────────────────┴─────────────────────────────────────────────┘

Tabela 12.7. Lista de operadores de comparação de strings na

Page 757: Referências Debian

expressão condicional

┌────────────────┬─────────────────────────────────────────────┐

equação condição para retornar o verdadeiro lógico │ │ │

├────────────────┼─────────────────────────────────────────────┤

-z <str> o comprimento de <str> é zero │ │ │

├────────────────┼─────────────────────────────────────────────┤

-n <str> o comprimento de <str> não é zero │ │ │

├────────────────┼─────────────────────────────────────────────┤

<str1> = <str2> <str1> and <str2> são iguais │ │ │

├────────────────┼─────────────────────────────────────────────┤

<str1> != <str2> <str1> and <str2> não são iguais │ │ │

├────────────────┼─────────────────────────────────────────────┤

<str1> < <str2> <str1> sorts before <str2> (locale dependent)│ │ │

├────────────────┼─────────────────────────────────────────────┤

<str1> > <str2> <str1> sorts after <str2> (locale dependent) │ │ │

└────────────────┴─────────────────────────────────────────────┘

Arithmetic integer comparison operators in the conditional

expression are "-eq", "-ne", "-lt", "-le", "-gt", and "-ge".

12.1.4. Ciclos da shell

Page 758: Referências Debian

There are several loop idioms to use in POSIX shell.

"for x in foo1 foo2 … ; do command ; done" loops by●

assigning items from the list "foo1 foo2 …" to variable "x"

and executing "command".

"while condition ; do command ; done" repeats "command"●

while "condition" is true.

"until condition ; do command ; done" repeats "command"●

while "condition" is not true.

"break" permite sair do ciclo.●

"continue" enables to resume the next iteration of the loop.●

Dica

The C-language like numeric iteration can be realized by using

seq(1) as the "foo1 foo2 …" generator.

Dica

See Secção 9.5.9, “Repeating a command looping over files”.

12.1.5. A sequência de processamento da linha de comandos da

shell

The shell processes a script roughly as the following sequence.

A shell lê uma linha.●

The shell groups a part of the line as one token if it is●

within "…" or '…'.

Page 759: Referências Debian

The shell splits other part of a line into tokens by the●

following.

Whitespaces: <space> <tab> <newline>○

Metacharacters: < > | ; & ( )○

The shell checks the reserved word for each token to adjust●

its behavior if not within "…" or '…'.

reserved word: if then elif else fi for in while unless○

do done case esac

The shell expands alias if not within "…" or '…'.●

The shell expands tilde if not within "…" or '…'.●

"~" → current user's home directory○

"~<user>" → <user>'s home directory○

The shell expands parameter to its value if not within '…'.●

parameter: "$PARAMETER" or "${PARAMETER}"○

The shell expands command substitution if not within '…'.●

"$( command )" → the output of "command"○

"` command `" → the output of "command"○

The shell expands pathname glob to matching file names if●

not within "…" or '…'.

* → quaisquer caracteres○

? → um caractere○

[…] → any one of the characters in "…"○

The shell looks up command from the following and execute●

Page 760: Referências Debian

it.

definição de função○

comando builtin○

executable file in "$PATH"○

The shell goes to the next line and repeats this process●

again from the top of this sequence.

Single quotes within double quotes have no effect.

Executing "set -x" in the shell or invoking the shell with "-x"

option make the shell to print all of commands executed. This is

quite handy for debugging.

12.1.6. Programas utilitários para script de shell

In order to make your shell program as portable as possible

across Debian system, it is good idea to limit utility programs

to ones provided by essential packages.

"aptitude search ~E" lists essential packages.●

"dpkg -L <package_name> |grep '/man/man.*/'" lists manpages●

for commands offered by <package_name> package.

Tabela 12.8. List of packages containing small utility programs

for shell scripts

┌────────────┬─────────┬───────┬───────────────────────────────┐

Page 761: Referências Debian

pacote popcon tamanho descrição │ │ │ │ │

├────────────┼─────────┼───────┼───────────────────────────────┤

coreutils * V:92, 13828 utilitários de núcleo GNU │ │ │ │ │

I:99 │ │ │ │ │

├────────────┼─────────┼───────┼───────────────────────────────┤

debianutils V:93, 260 utilitários variados │ │ │ │ │

* I:99 específicos da Debian │ │ │ │ │

├────────────┼─────────┼───────┼───────────────────────────────┤

bsdmainutils V:81, 768 colecção de mais utilitários do│ │ │ │ │

* I:99 FreeBSD │ │ │ │ │

├────────────┼─────────┼───────┼───────────────────────────────┤

bsdutils * V:77, 196 utilitários básicos do │ │ │ │ │

I:99 4.4BSD-Lite │ │ │ │ │

├────────────┼─────────┼───────┼───────────────────────────────┤

moreutils * V:0.3, 220 utilitários Unix adicionais │ │ │ │ │

I:1.5 │ │ │ │ │

└────────────┴─────────┴───────┴───────────────────────────────┘

Dica

Although moreutils may not exist ouside of Debian, it offers

interesting small programs. Most notable one is sponge(8). See

Secção 1.6.4, “Substituição global com expressões regulares”.

Page 762: Referências Debian

12.1.7. Diálogo do script de shell

The user interface of a simple shell program can be improved

from dull interaction by echo and read commands to more

interactive one by using one of the so-called dialog program

etc.

Tabela 12.9. Lista de programas de interface de utilizador

┌─────────┬───────┬───────┬────────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

x11-utils V:26, 652 xmessage(1): display a message or │ │ │ │ │

* I:53 query in a window (X) │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

whiptail V:42, 104 displays user-friendly dialog boxes │ │ │ │ │

* I:99 from shell scripts (newt) │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

dialog * V:4, 1592 displays user-friendly dialog boxes │ │ │ │ │

I:25 from shell scripts (ncurses) │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

zenity * V:8, 4992 display graphical dialog boxes from │ │ │ │ │

I:41 shell scripts (gtk2.0) │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

V:0.01, Shell Scripts Frontend Tool (wrapper│ │ │ │ │

Page 763: Referências Debian

ssft * I:0.11 152 for zenity, kdialog, and dialog with│ │ │ │ │

gettext) │ │ │ │ │

├─────────┼───────┼───────┼────────────────────────────────────┤

gettext * V:8, 7272 "/usr/bin/gettext.sh": traduz │ │ │ │ │

I:46 mensagem │ │ │ │ │

└─────────┴───────┴───────┴────────────────────────────────────┘

12.1.8. Shell script example with zenity

Here is a simple script which creates ISO image with RS02 data

supplemented by dvdisaster(1).

#!/bin/sh -e

# gmkrs02 : Copyright (C) 2007 Osamu Aoki <[email protected]>, Public Domain

#set -x

error_exit()

{

echo "$1" >&2

exit 1

}

# Initialize variables

DATA_ISO="$HOME/Desktop/iso-$$.img"

LABEL=$(date +%Y%m%d-%H%M%S-%Z)

if [ $# != 0 ] && [ -d "$1" ]; then

DATA_SRC="$1"

else

Page 764: Referências Debian

# Select directory for creating ISO image from folder on desktop

DATA_SRC=$(zenity --file-selection --directory \

--title="Select the directory tree root to create ISO image") \

|| error_exit "Exit on directory selection"

fi

# Check size of archive

xterm -T "Check size $DATA_SRC" -e du -s $DATA_SRC/*

SIZE=$(($(du -s $DATA_SRC | awk '{print $1}')/1024))

if [ $SIZE -le 520 ] ; then

zenity --info --title="Dvdisaster RS02" --width 640 --height 400 \

--text="The data size is good for CD backup:\\n $SIZE MB"

elif [ $SIZE -le 3500 ]; then

zenity --info --title="Dvdisaster RS02" --width 640 --height 400 \

--text="The data size is good for DVD backup :\\n $SIZE MB"

else

zenity --info --title="Dvdisaster RS02" --width 640 --height 400 \

--text="The data size is too big to backup : $SIZE MB"

error_exit "The data size is too big to backup :\\n $SIZE MB"

fi

# only xterm is sure to have working -e option

# Create raw ISO image

rm -f "$DATA_ISO" || true

xterm -T "genisoimage $DATA_ISO" \

-e genisoimage -r -J -V "$LABEL" -o "$DATA_ISO" "$DATA_SRC"

# Create RS02 supplemental redundancy

xterm -T "dvdisaster $DATA_ISO" -e dvdisaster -i "$DATA_ISO" -mRS02 -c

zenity --info --title="Dvdisaster RS02" --width 640 --height 400 \

--text="ISO/RS02 data ($SIZE MB) \\n created at: $DATA_ISO"

# EOF

Page 765: Referências Debian

You may wish to create launcher on the desktop with command set

something like "/usr/local/bin/gmkrs02 %d".

12.2. Make

Make is a utility to maintain groups of programs. Upon execution

of make(1), make read the rule file, "Makefile", and updates a

target if it depends on prerequisite files that have been

modified since the target was last modified, or if the target

does not exist. The execution of these updates may occur

concurrently.

A regra de sintaxe do ficheiro é a seguinte.

target: [ prerequisites ... ]

[TAB] command1

[TAB] -command2 # ignore errors

[TAB] @command3 # suppress echoing

Here " [TAB] " is a TAB code. Each line is interpreted by the

shell after make variable substitution. Use "\" at the end of a

line to continue the script. Use "$$" to enter "$" for

environment values for a shell script.

Implicit rules for the target and prerequisites can be written,

for example, by the following.

%.o: %.c header.h

Page 766: Referências Debian

Here, the target contains the character "%" (exactly one of

them). The "%" can match any nonempty substring in the actual

target filenames. The prerequisites likewise use "%" to show how

their names relate to the actual target name.

Tabela 12.10. Lista de variáveis automáticas do make

┌───────────────────┬──────────────────────────────────────┐

variável automática valor │ │ │

├───────────────────┼──────────────────────────────────────┤

$@ alvo │ │ │

├───────────────────┼──────────────────────────────────────┤

$< primeiro pre-requisito │ │ │

├───────────────────┼──────────────────────────────────────┤

$? todos os novos pre-requisitos │ │ │

├───────────────────┼──────────────────────────────────────┤

$^ todos os pre-requisitos │ │ │

├───────────────────┼──────────────────────────────────────┤

$* "%" matched stem in the target pattern│ │ │

└───────────────────┴──────────────────────────────────────┘

Tabela 12.11. Lista de expansões da variável do make

Page 767: Referências Debian

┌────────────────────┬───────────────────┐

expansão da variável descrição │ │ │

├────────────────────┼───────────────────┤

foo1 := bar expansão de uma vez│ │ │

├────────────────────┼───────────────────┤

foo2 = bar expansão recursiva │ │ │

├────────────────────┼───────────────────┤

foo3 += bar acrescentar │ │ │

└────────────────────┴───────────────────┘

Run "make -p -f/dev/null" to see automatic internal rules.

12.3. C

You can set up proper environment to compile programs written in

the C programming language by the following.

# apt-get install glibc-doc manpages-dev libc6-dev gcc build-essential

The libc6-dev package, i.e., GNU C Library, provides C standard

library which is collection of header files and library routines

used by the C programming language.

Veja referências para C nos seguintes.

"info libc" (Referência de funções da biblioteca C)●

gcc(1) e "info gcc"●

each_C_library_function_name(3)●

Page 768: Referências Debian

Kernighan & Ritchie, "The C Programming Language", 2nd●

edition (Prentice Hall)

12.3.1. Programa C simples (gcc)

A simple example "example.c" can compiled with a library "libm"

into an executable "run_example" by the following.

$ cat > example.c << EOF

#include <stdio.h>

#include <math.h>

#include <string.h>

int main(int argc, char **argv, char **envp){

double x;

char y[11];

x=sqrt(argc+7.5);

strncpy(y, argv[0], 10); /* prevent buffer overflow */

y[10] = '\0'; /* fill to make sure string ends with '\0' */

printf("%5i, %5.3f, %10s, %10s\n", argc, x, y, argv[1]);

return 0;

}

EOF

$ gcc -Wall -g -o run_example example.c -lm

$ ./run_example

1, 2.915, ./run_exam, (null)

$ ./run_example 1234567890qwerty

2, 3.082, ./run_exam, 1234567890qwerty

Page 769: Referências Debian

Here, "-lm" is needed to link library "/usr/lib/libm.so" from

the libc6 package for sqrt(3). The actual library is in "/lib/"

with filename "libm.so.6", which is a symlink to "libm-2.7.so".

Look at the last parameter in the output text. There are more

than 10 characters even though "%10s" is specified.

The use of pointer memory operation functions without boundary

checks, such as sprintf(3) and strcpy(3), is deprecated to

prevent buffer overflow exploits that leverage the above overrun

effects. Instead, use snprintf(3) and strncpy(3).

12.4. Depuração

Debug is important part of programing activities. Knowing how to

debug programs makes you a good Debian user who can produce

meaningful bug reports.

12.4.1. Execução gdb básica

O depurador principal em Debian é o gdb(1) que lhe permite

inspeccionar um programa enquanto ele é executado.

Vamos instalar o gdb e programas relacionados com o seguinte.

# apt-get install gdb gdb-doc build-essential devscripts

Good tutorial of gdb is provided by "info gdb" or found

elsewhere on the web. Here is a simple example of using gdb(1)

Page 770: Referências Debian

on a "program" compiled with the "-g" option to produce

debugging information.

$ gdb program

(gdb) b 1 # set break point at line 1

(gdb) run args # run program with args

(gdb) next # next line

...

(gdb) step # step forward

...

(gdb) p parm # print parm

...

(gdb) p parm=12 # set value to 12

...

(gdb) quit

Dica

Many gdb(1) commands can be abbreviated. Tab expansion works as

in the shell.

12.4.2. Depurar o pacote Debian

Since all installed binaries should be stripped on the Debian

system by default, most debugging symbols are removed in the

normal package. In order to debug Debian packages with gdb(1),

corresponding *-dbg packages need to be installed (e.g.

libc6-dbg in the case of libc6).

Page 771: Referências Debian

If a package to be debugged does not provide its *-dbg package,

you need to install it after rebuilding it by the following.

$ mkdir /path/new ; cd /path/new

$ sudo apt-get update

$ sudo apt-get dist-upgrade

$ sudo apt-get install fakeroot devscripts build-essential

$ sudo apt-get build-dep nome_do_pacote_fonte

$ apt-get source nome_do_pacote

$ cd nome_do_pacote*

Corrigir bugs se necessário

Bump package version to one which does not collide with official

Debian versions, e.g. one appended with "+debug1" when

recompiling existing package version, or one appended with

"~pre1" when compiling unreleased package version by the

following.

$ dch -i

Compile e instale pacotes com símbolos de depuração com o

seguinte.

$ export DEB_BUILD_OPTIONS=nostrip,noopt

$ debuild

$ cd ..

$ sudo debi nome_do_pacote*.changes

Page 772: Referências Debian

You need to check build scripts of the package and ensure to use

"CFLAGS=-g -Wall" for compiling binaries.

12.4.3. Obtaining backtrace

When you encounter program crash, reporting bug report with

cut-and-pasted backtrace information is a good idea.

The backtrace can be obtained by the following steps.

Correr o programa sob gdb(1).●

Reproduzir o erro (crash).●

It causes you to be dropped back to the gdb prompt.○

Type "bt" at the gdb prompt.●

In case of program freeze, you can crash the program by pressing

Ctrl-C in the terminal running gdb to obtain gdb prompt.

Dica

Often, you see a backtrace where one or more of the top lines

are in "malloc()" or "g_malloc()". When this happens, chances

are your backtrace isn't very useful. The easiest way to find

some useful information is to set the environment variable

"$MALLOC_CHECK_" to a value of 2 (malloc(3)). You can do this

while running gdb by doing the following.

$ MALLOC_CHECK_=2 gdb hello

Page 773: Referências Debian

12.4.4. Comandos gdb avançados

Tabela 12.12. Lista de comandos gdb avançados

┌───────────────────┬──────────────────────────────────────────┐

comando descrição dos objectivos do comando │ │ │

├───────────────────┼──────────────────────────────────────────┤

(gdb) thread apply get a backtrace for all threads for │ │ │

all bt multi-threaded program │ │ │

├───────────────────┼──────────────────────────────────────────┤

(gdb) bt full get parameters came on the stack of │ │ │

function calls │ │ │

├───────────────────┼──────────────────────────────────────────┤

(gdb) thread apply get a backtrace and parameters as the │ │ │

all bt full combination of the preceding options │ │ │

├───────────────────┼──────────────────────────────────────────┤

(gdb) thread apply get a backtrace and parameters for top 10 │ │ │

all bt full 10 calls to cut off irrelevant output │ │ │

├───────────────────┼──────────────────────────────────────────┤

(gdb) set logging write log of gdb output to a file (the │ │ │

on default is "gdb.txt") │ │ │

└───────────────────┴──────────────────────────────────────────┘

Page 774: Referências Debian

12.4.5. Depurar Erros do X

If a GNOME program preview1 has received an X error, you should

see a message as follows.

O programa 'preview1' recebeu um erro do X Window System.

If this is the case, you can try running the program with

"--sync", and break on the "gdk_x_error" function in order to

obtain a backtrace.

12.4.6. Verificar a dependência em bibliotecas

Use ldd(1) to find out a program's dependency on libraries by

the followings.

$ ldd /bin/ls

librt.so.1 => /lib/librt.so.1 (0x4001e000)

libc.so.6 => /lib/libc.so.6 (0x40030000)

libpthread.so.0 => /lib/libpthread.so.0 (0x40153000)

/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

For ls(1) to work in a `chroot`ed environment, the above

libraries must be available in your `chroot`ed environment.

Veja Secção 9.5.6, “Rastear as actividades de programas”.

12.4.7. Ferramentas de detecção de fugas de memória

Page 775: Referências Debian

Aqui estão várias ferramentas de detecção de fugas de memória em

Debian.

Tabela 12.13. Lista de ferramentas de detecção de fugas de

memória

┌──────────────┬───────┬───────┬───────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

libc6-dev * V:46, 11292 mtrace(1): funcionalidades de │ │ │ │ │

I:68 depuração do malloc em glibc │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

valgrind * V:1.3, 136416 depurador e perfilador de │ │ │ │ │

I:6 memória │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

V:0.3, Rastreador de fugas de memória │ │ │ │ │

kmtrace * I:2 324 do KDE que usa o mtrace(1) da │ │ │ │ │

glibc │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

alleyoop * V:0.05, 596 Frontend do GNOME para o │ │ │ │ │

I:0.3 verificador de memória Valgrind│ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

electric-fence V:0.05, 120 o depurador malloc(3) │ │ │ │ │

* I:0.8 │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

Page 776: Referências Debian

leaktracer * V:0.01, 116 rastreador de fugas de memória │ │ │ │ │

I:0.11 para programas C++ │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

libdmalloc5 * V:0.01, 356 biblioteca de depuração de │ │ │ │ │

I:0.2 alocação de memória │ │ │ │ │

├──────────────┼───────┼───────┼───────────────────────────────┤

mpatrolc2 * V:0.00, 3592 biblioteca para depurar │ │ │ │ │

I:0.01 alocações de memória │ │ │ │ │

└──────────────┴───────┴───────┴───────────────────────────────┘

12.4.8. Ferramentas de análise de código estático

There are lint like tools for static code analysis.

Tabela 12.14. Lista de ferramentas para análise de código

estático

┌─────────────┬───────┬───────┬────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.06, ferramenta para verificação │ │ │ │ │

splint * I:0.5 1836 estática de programas C para │ │ │ │ │

bugs │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

Page 777: Referências Debian

V:0.06, rough Auditing Tool for Security│ │ │ │ │

rats * I:0.2 876 (C, C++, PHP, Perl, and Python │ │ │ │ │

code) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

V:0.01, ferramenta para examinar código │ │ │ │ │

flawfinder * I:0.15 192 fonte C/C++ e procurar por │ │ │ │ │

fraquezas na segurança │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

perl * V:88, 18528 interpreter with internal static│ │ │ │ │

I:99 code checker: B::Lint(3perl) │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

pylint * V:0.2, 576 Verificador estático de código │ │ │ │ │

I:0.7 Python │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

jlint * V:0.01, 156 Verificador de programa Java │ │ │ │ │

I:0.09 │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

weblint-perl V:0.10, 28 Verificado de sintaxe e estilo │ │ │ │ │

* I:0.7 mínimo para HTML │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

linklint * V:0.05, 432 fast link checker and web site │ │ │ │ │

I:0.3 maintenance tool │ │ │ │ │

├─────────────┼───────┼───────┼────────────────────────────────┤

libxml2-utils V:3, 160 utilities with xmllint(1) to │ │ │ │ │

* I:49 validate XML files │ │ │ │ │

Page 778: Referências Debian

└─────────────┴───────┴───────┴────────────────────────────────┘

12.4.9. Disassemble binary

You can disassemble binary code with objdump(1) by the

following.

$ objdump -m i386 -b binary -D /usr/lib/grub/x86_64-pc/stage1

Nota

gdb(1) may be used to disassemble code interactively.

12.5. Flex — um Lex melhor.

Flex is a Lex-compatible fast lexical analyzer generator.

Tutorial for flex(1) can be found in "info flex".

You need to provide your own "main()" and "yywrap()". Otherwise,

your flex program should look like this to compile without a

library. This is because that "yywrap" is a macro and "%option

main" turns on "%option noyywrap" implicitly.

%option main

%%

.|\n ECHO ;

Page 779: Referências Debian

%%

Alternatively, you may compile with the "-lfl" linker option at

the end of your cc(1) command line (like AT&T-Lex with "-ll").

No "%option" is needed in this case.

12.6. Bison — um Yacc melhor

Several packages provide a Yacc-compatible lookahead LR parser

or LALR parser generator in Debian.

Tabela 12.15. List of Yacc-compatible LALR parser generators

┌──────┬───────────┬───────┬───────────────────────────────────┐

pacote popcon tamanho descrição │ │ │ │ │

├──────┼───────────┼───────┼───────────────────────────────────┤

bison V:2, I:15 1504 GNU LALR parser generator │ │ │ │ │

* │ │ │ │ │

├──────┼───────────┼───────┼───────────────────────────────────┤

byacc V:0.09, 168 Berkeley LALR parser generator │ │ │ │ │

* I:1.2 │ │ │ │ │

├──────┼───────────┼───────┼───────────────────────────────────┤

btyacc V:0.00, 248 backtracking parser generator based│ │ │ │ │

* I:0.07 on byacc │ │ │ │ │

└──────┴───────────┴───────┴───────────────────────────────────┘

Page 780: Referências Debian

O tutorial para o bison(1) pode ser encontrado em "info bison".

You need to provide your own "main()" and "yyerror()". "main()"

calls "yyparse()" which calls "yylex()", usually created with

Flex.

%%

%%

12.7. Autoconf

Autoconf is a tool for producing shell scripts that

automatically configure software source code packages to adapt

to many kinds of Unix-like systems using the entire GNU build

system.

autoconf(1) produces the configuration script "configure".

"configure" automatically creates a customized "Makefile" using

the "Makefile.in" template.

12.7.1. Compilar e instalar o programa

Atenção

Não substitua ficheiros do sistema com os seus programas

compilados quando os instalar.

Page 781: Referências Debian

Debian does not touch files in "/usr/local/" or "/opt". So if

you compile a program from source, install it into "/usr/local/"

so it does not interfere with Debian.

$ cd src

$ ./configure --prefix=/usr/local

$ make

$ make install # this puts the files in the system

12.7.2. Desinstalar o programa

If you have the original source and if it uses autoconf(1)/

automake(1) and if you can remember how you configured it,

execute as follows to uninstall the program.

$ ./configure "todas-as-opções-que-fornecer"

# make uninstall

Alternatively, if you are absolutely sure that the install

process puts files only under "/usr/local/" and there is nothing

important there, you can erase all its contents by the

following.

# find /usr/local -type f -print0 | xargs -0 rm -f

If you are not sure where files are installed, you should

consider using checkinstall(8) from the checkinstall package,

which provides a clean path for the uninstall. It now supports

to create a Debian package with "-D" option.

Page 782: Referências Debian

12.8. Perl short script madness

Although any AWK scripts can be automatically rewritten in Perl

using a2p(1), one-liner AWK scripts are best converted to

one-liner Perl scripts manually.

Let's think following AWK script snippet.

awk '($2=="1957") { print $3 }' |

Isto é equivalente a qualquer uma das seguintes linhas.

perl -ne '@f=split; if ($f[1] eq "1957") { print "$f[2]\n"}' |

perl -ne 'if ((@f=split)[1] eq "1957") { print "$f[2]\n"}' |

perl -ne '@f=split; print $f[2] if ( $f[1]==1957 )' |

perl -lane 'print $F[2] if $F[1] eq "1957"' |

perl -lane 'print$F[2]if$F[1]eq+1957' |

Este último é um enigma. Aproveitei-me das seguintes

funcionalidades do Perl.

O espaço em branco é opcional.●

A conversão automática existe de números para string.●

Page 783: Referências Debian

See perlrun(1) for the command-line options. For more crazy Perl

scripts, Perl Golf may be interesting.

12.9. Web

Basic interactive dynamic web pages can be made as follows.

Queries are presented to the browser user using HTML forms.●

Filling and clicking on the form entries sends one of the●

following URL string with encoded parameters from the

browser to the web server.

"http://www.foo.dom/cgi-bin/program.pl?VAR1=VAL1&VAR2=○

VAL2&VAR3=VAL3"

"http://www.foo.dom/cgi-bin/program.py?VAR1=VAL1&VAR2=○

VAL2&VAR3=VAL3"

"http://www.foo.dom/program.php?VAR1=VAL1&VAR2=VAL2&VAR3○

=VAL3"

"%nn" in URL is replaced with a character with hexadecimal●

nn value.

A variável de ambiente está definida como: "QUERY_STRING=●

"VAR1=VAL1 VAR2=VAL2 VAR3=VAL3"".

CGI program (any one of "program.*") on the web server●

executes itself with the environment variable

"$QUERY_STRING".

stdout of CGI program is sent to the web browser and is●

presented as an interactive dynamic web page.

For security reasons it is better not to hand craft new hacks

Page 784: Referências Debian

for parsing CGI parameters. There are established modules for

them in Perl and Python. PHP comes with these functionalities.

When client data storage is needed, HTTP cookies are used. When

client side data processing is needed, Javascript is frequently

used.

For more, see the Common Gateway Interface, The Apache Software

Foundation, and JavaScript.

Searching "CGI tutorial" on Google by typing encoded URL http://

www.google.com/search?hl=en&ie=UTF-8&q=CGI+tutorial directly to

the browser address is a good way to see the CGI script in

action on the Google server.

12.10. A tradução do código fonte

Existem programas para converter códigos fonte.

Tabela 12.16. Lista de ferramentas de tradução de código fonte

┌─────────┬───────┬───────┬─────────┬──────────────────────────┐

pacote popcon tamanho palavra descrição │ │ │ │ │ │

chave │ │ │ │ │ │

├─────────┼───────┼───────┼─────────┼──────────────────────────┤

perl * V:88, 18528 AWK→PERL convert source codes from │ │ │ │ │ │

I:99 AWK to PERL: a2p(1) │ │ │ │ │ │

├─────────┼───────┼───────┼─────────┼──────────────────────────┤

Page 785: Referências Debian

V:0.12, convert source codes from │ │ │ │ │ │

f2c * I:1.2 448 FORTRAN→C FORTRAN 77 to C/C++: f2c │ │ │ │ │ │

(1) │ │ │ │ │ │

├─────────┼───────┼───────┼─────────┼──────────────────────────┤

protoize V:0.00, 100 ANSI C Cria/remove protótipos │ │ │ │ │ │

* I:0.09 ANSI de código C │ │ │ │ │ │

├─────────┼───────┼───────┼─────────┼──────────────────────────┤

intel2gas V:0.01, converter from NASM (Intel│ │ │ │ │ │

* I:0.07 344 intel→gas format) to the GNU │ │ │ │ │ │

Assembler (GAS) │ │ │ │ │ │

└─────────┴───────┴───────┴─────────┴──────────────────────────┘

12.11. Criando um pacote Debian

Se você deseja criar um pacote debian, leia o seguinte.

Capítulo 2, Gestão de pacotes Debian para compreender o●

sistema básico de pacotes

Secção 2.7.10, “Portando um pacote para o sistema stable”●

para compreender o processo de portar básico

Secção 9.8.4, “Sistema chroot” para compreender as técnicas●

de chroot básicas

debuild(1), pbuilder(1) e pdebuild(1)●

Secção 12.4.2, “Depurar o pacote Debian” para recompilar●

para depuração

Guia dos Novos Maintainers da Debian como tutorial (o pacote●

Page 786: Referências Debian

maint-guide)

Referência de Programadores da Debian (o pacote●

developers-reference)

Manual de Políticas Debian (o pacote debian-policy)●

Existem pacotes como os dh-make, dh-make-perl, etc., que ajudam

no processo em empacotamento.

Apêndice A. Apêndice

Aqui estão os bastidores deste documento.

A.1. o labirinto Debian

The Linux system is a very powerful computing platform for a

networked computer. However, learning how to use all its

capabilities is not easy. Setting up the LPR printer with

non-PostScript printer was a good example of stumble points.

(There are no issues anymore since newer installations use new

CUPS system.)

There is a complete, detailed map called the "SOURCE CODE". This

is very accurate but very hard to understand. There are also

references called HOWTO and mini-HOWTO. They are easier to

understand but tend to give too much detail and lose the big

picture. I sometimes have a problem finding the right section in

a long HOWTO when I need a few commands to invoke.

I hope this "Debian Reference (version 2)" provides a good

Page 787: Referências Debian

starting direction for people in the Debian maze.

A.2. História do Copyright

Debian Reference was initiated by Osamu Aoki <osamu at debian

dot org> as a personal system administration memo. Many contents

came from the knowledge I gained from the debian-user mailing

list and other Debian resources.

Following a suggestion from Josip Rodin, who was very active

with the Debian Documentation Project (DDP), "Debian Reference

(version 1, 2001-2007)" was created as a part of DDP documents.

Após 6 anos, Osamu percebeu que a "Debian Reference (versão 1)"

estava ultrapassada e começo a reescrever muitos conteúdos. A

nova "Debian Reference (versão 2)" é lançada em 2008.

Os conteúdos do tutorial pode ser rastreados até à sua origem e

inspiração com o seguinte.

"Linux User's Guide" by Larry Greenfield (December 1996)●

tornado obsoleto pelo "Debian Tutorial"○

"Debian Tutorial" by Havoc Pennington. (11 December, 1998)●

parcialmente escrito por Oliver Elphick, Ole Tetlie,○

James Treacy, Craig Sawyer, e Ivan E. Moore II

tornado obsoleto por "Debian GNU/Linux: Guia de○

Instalação e Utilização"

Page 788: Referências Debian

"Debian GNU/Linux: Guide to Installation and Usage" by John●

Goerzen and Ossama Othman (1999)

tornado obsoleto pela "Debian Reference (versão 1)"○

The package and archive description can trace some of their

origin and their inspiration in following.

"FAQ da Debian" (versão de Março 2002, quando isto era●

mantido por Josip Rodin)

The other contents can trace some of their origin and their

inspiration in following.

"Debian Reference (versão 1)" por Osamu Aoki (2001–2007)●

tornado obsoleto por esta nova "Debian Reference (versão○

2)"

A "Debian Reference (versão 1)" anterior foi criada com muitos

contribuintes.

a maior contribuição de conteúdos em tópicos de configuração●

de rede por Thomas Hood

contribuição significante de conteúdos em tópicos●

relacionados com X e VCS por Brian Nelson

a ajuda na construção de scripts e muitas correcções no●

conteúdo por Jens Seidel

extensive proofreading by David Sewell●

Page 789: Referências Debian

muitas contribuições pelos tradutores, contribuintes, e●

relatórios de bugs

Many manual pages and info pages on the Debian system were used

as the primary references to write this document. To the extent

Osamu Aoki considered within the fair use, many parts of them,

especially command definitions, were used as phrase pieces after

careful editorial efforts to fit them into the style and the

objective of this document.

A descrição do depurador gdb foi expandida usando Conteúdos wiki

Debian em backtrace com consentimento por Ari Pollak, Loïc

Minier, de Dafydd Harries.

O conteúdo do "Debian Reference (versão 2)" é maioritariamente

trabalho meu com excepção do descrito acima. Este foi também

actualizado pelos contribuintes.

O Documento "Debian Reference (versão 2)" foi traduzido por

Américo Monteiro a_monteiro_AT_netcabo.pt.

O autor, Osamu Aoki, agradece a todos os que ajudaram a tornar

possível este documento.

A.3. Formato do documento

The source of the English original document is currently written

in AsciiDoc text files. AsciiDoc is used as convenience only

since it is less typing than straight XML and supports table in

Page 790: Referências Debian

the very intuitive format. You should think XML and PO files as

real source files. Via build script, it is converted to DocBook

XML format and automatically generated data are inserted to form

a final Docbook XML source. This final Docbook XML source can be

converted to HTML, plain text, PostScript, and PDF. Currently,

only HTML and plain text conversions are enabled.