Capítulo 9. Dicas do sistema

Índice

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

Aqui, eu descrevo dicas básicas para configurar e gerir sistemas, a maioria a partir da consola.

9.1. O programa screen

screen(1) is a very useful tool for people to access remote sites via unreliable or intermittent connections since it support interrupted network connections.

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

pacote popcon tamanho descrição
screen * V:11, I:34 952 terminal multiplexador com emulação de 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.
  3. You execute multiple programs in screen windows created with ^A c ("Control-A" followed by "c").
  4. You switch among the multiple screen windows by ^A n ("Control-A" followed by "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] 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 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 atalho significado
^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
^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 detach screen session from the terminal
^A DD detach screen session and log out

Veja screen(1) para detalhes.

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

9.2.1. O daemon de log

Many programs record their activities under the "/var/log/" directory.

  • 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

Here are notable log analyzers ("~Gsecurity::log-analyzer" in aptitude(8)).

Tabela 9.3. Lista de analisadores de log do sistema

pacote popcon tamanho descrição
logwatch * V:3, I:3 2592 analisador de log com saída bonita escrito em Perl
fail2ban * V:4, I:5 660 banir IPs que causam erros de autenticação múltipla
analog * V:1.0, I:16 4520 analisador de log do servidor web
awstats * V:1.8, I:3 5200 analisador de logs de servidor web poderoso e cheio de funcionalidades
sarg * V:1.9, I:2 644 squid analysis report generator
pflogsumm * V:0.3, I:0.7 160 Postfix log entry summarizer
syslog-summary * V:0.2, I:0.9 84 sumariza o conteúdo do um ficheiro de log do syslog
lire * V:0.15, I:0.17 5304 full-featured log analyzer and report generator
fwlogwatch * V:0.10, I:0.2 440 analisador de log da firewall
squidview * V:0.11, I:0.6 244 monitor and analyze squid access.log files
visitors * V:0.09, I:0.3 228 analisador de log do servidor web rápido
swatch * V:0.06, I:0.2 112 log file viewer with regexp matching, highlighting, and hooks
crm114 * V:0.06, I:0.18 1300 Controllable Regex Mutilator and Spam Filter (CRM114)
icmpinfo * V:0.04, I:0.2 84 interpretar mensagens ICMP

[Nota] 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.

$ script
Script started, file is 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] Dica

Some x-terminal-emulator such as gnome-terminal can record. You may wish to extend line buffer for scrollback.

[Dica] 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] 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 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] 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 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 hora localização mostra a hora e data
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
+%d.%m.%y %H:%M qualquer 19.01.09 00:15
+%d.%b.%y %H:%M C ou en_US.UTF-8 19.Jan.09 00:15
+%d.%b.%y %H:%M es_ES.UTF-8 19.ene.09 00:15

[Dica] 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] 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")
$ 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 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] 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.

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

There are specialized tools to record changes in configuration files with help of DVCS system.

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

pacote popcon tamanho descrição
etckeeper * V:1.0, I:1.5 376 store configuration files and their metadata with Git (default), Mercurial, or Bazaar (new)
changetrack * V:0.07, I:0.09 152 armazenar ficheiros de 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] Dica

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] 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 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, I:99 2216 Não suportado vários utilitários de sistema incluindo fdisk(8) e cfdisk(8)
parted * V:1.0, I:9 236 Suportado GNU Parted programa de redimensionamento de partições do disco
gparted * V:3, I:31 4548 Suportado Editor de partições do GNOME baseado na libparted
qtparted * V:0.10, I:0.9 NOT_FOUND Suportado Editor de partições do KDE baseado na libparted
gptsync * V:0.01, I:0.18 72 Suportado sincroniza a tabela de partições MBR clássica com a GPT
kpartx * V:1.0, I:1.8 132 Suportado programa para criar mapeamentos de dispositivo para partições

[Cuidado] 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] 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 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.

[Dica] Dica

Você pode testar o UUID de um dispositivo especial de bloco com blkid(8).

[Dica] 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 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, I:99 1924 utilitários para os sistemas de ficheiros ext2/ext3/ext4
reiserfsprogs * V:2, I:8 1200 utilitários para o sistema de ficheiros Reiserfs
dosfstools * V:3, I:31 192 utilitários para o sistema de ficheiros FAT. (Microsoft: MS-DOS, Windows)
xfsprogs * V:2, I:10 3272 utilitários para o sistema de ficheiros XFS. (SGI: IRIX)
ntfsprogs * V:3, I:20 676 utilitários para o sistema de ficheiros NTFS. (Microsoft: Windows NT, …)
jfsutils * V:0.5, I:2 1112 utilitários para o sistema de ficheiros JFS. (IBM: AIX, OS/2)
reiser4progs * V:0.09, I:0.7 1264 utilitários para o sistema de ficheiros Reiser4
hfsprogs * V:0.06, I:0.8 316 utilitários para os sistemas de ficheiros HFS e HFS Plus. (Apple: Mac OS)
btrfs-tools * V:0.3, I:0.6 1288 utilitários para o sistema de ficheiros btrfs
zerofree * V:0.10, I:0.7 56 programa para zerar blocos livres de sistemas de ficheiros ext2/3

[Dica] 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] 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] 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

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] Cuidado

Geralmente não é seguro correr o fsck em sistemas de ficheiros montados.

[Dica] Dica

Verifique os ficheiros em "/var/log/fsck/" para os resultados do comando fsck(8) executado a partir do script de arranque.

[Dica] 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: "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] 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 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] 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] 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] Atenção

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

You can test write cache feature of a hard disk, e.g. "/dev/sda", by "hdparm -W /dev/sda". You can disable its write cache feature with "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).

    • Let's assume a hard disk drive to be monitored as "/dev/hda".
  4. Check the output of "smartctl -a /dev/hda" to see if SMART feature is actually enabled.

    • If not, enable it by "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"
    • restart the smartd(8) daemon by "sudo /etc/init.d/smartmontools restart".
[Dica] Dica

The smartd(8) daemon can be customized with the /etc/smartd.conf file including how to be notified of warnings.

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] Cuidado

Deployment of the current LVM system may degrade guarantee 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] 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 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] 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] Cuidado

Use of aufs for long term data storage is not good idea since it is under development and its design change may introduce issues.

[Dica] 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] 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

pacote popcon tamanho descrição
cryptsetup * V:3, I:5 1172 utilities for encrypted block device (dm-crypt / LUKS)
cryptmount * V:0.2, I:0.5 360 utilities for encrypted block device (dm-crypt / LUKS) with focus on mount/unmount by normal users
ecryptfs-utils * V:0.2, I:0.3 416 utilities for encrypted stacked 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] Cuidado

A encriptação de dados custa tempo da CPU e etc. Por favor pese os seus benefícios e custos.

[Nota] 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] 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/
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] 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.

# 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 trabalho.
  • Desactive "~/Private/" ao executar ecryptfs-umount-private(1).
  • Active "~/Private/" ao emitir "ecryptfs-mount-private" quando necessitar de dados encriptados.
[Dica] 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

Insira a seguinte linha na primeira linha activa em "/etc/pam.d/common-password".

password required pam_ecryptfs.so

Isto é bastante conveniente.

[Atenção] Atenção

Configuration errors of PAM may lock you out of your own system. See Capítulo 4, Autenticação.

[Cuidado] 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 as actividades de programas

pacote popcon tamanho descrição
coreutils * V:92, I:99 13828 nice(1): correr um programa com prioridade de agendamento modificada
bsdutils * V:77, I:99 196 renice(1): modifica a prioridade de agendamento de um processo em execução
procps * V:86, I:99 772 "/proc" utilitários de sistema de ficheiros: ps(1), top(1), kill(1) , watch(1), …
psmisc * V:47, I:88 716 "/proc" utilitários de sistema de ficheiros: killall(1), fuser(1), peekfd(1), pstree(1)
time * V:6, I:84 152 time(1): run a program to report system resource usages with respect to time
sysstat * V:4, I:9 872 sar(1), iostat(1), mpstat(1), …: ferramentas de performance do sistema para Linux
isag * V:0.07, I:0.4 152 Interactive System Activity Grapher para sysstat
lsof * V:16, I:90 444 lsof(8): lista os ficheiro abertos por um processo em execução usando a opção "-p"
strace * V:5, I:39 396 strace(1): rastreia chamadas e sinais do sistema
ltrace * V:0.3, I:2 188 ltrace(1): rastreia chamadas de bibliotecas
xtrace * V:0.02, I:0.18 372 xtrace(1): rastreia a comunicação entre cliente X11 e servidor
powertop * V:0.7, I:12 524 powertop(1): informação sobre sistema de energia usado em portáteis baseados em Intel
cron * V:91, I:99 240 run processes according to a schedule in background from cron(8) daemon
anacron * V:41, I:44 120 agenda de comandos tipo cron para sistemas que não funcionam 24 horas por dia
at * V:50, I:83 220 at(1) or batch(1): run a job at a specified time or below certain load level

[Dica] Dica

The procps packages provide very basics of monitoring, controlling, and starting program activities. You should learn all of them.

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

9.5.2. A prioridade de agendamento

A nice value is used to control the scheduling priority for the process.

Tabela 9.11. Lista de valores nice para a prioridade de agendamento

o valor nice prioridade de agendamento
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 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

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.

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

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

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:
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
#!/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] 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 check points for customizing this process.

  • Menu de configuração da aplicação:

    • GNOME desktop: "System" → "Preferences" → "Preferred Application"
    • 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] Dica

update-mime(8) updates the "/etc/mailcap" file using "/etc/mailcap.order" file (see mailcap.order(5)).

[Dica] Dica

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] 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

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.

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] 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] Dica

For scheduled system maintenance scripts, you can run them periodically from root account by placing such scripts in "/etc/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 Alt-SysRq descrição da acção
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
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] Cuidado

The Alt-SysRq feature may be considered a security risk by 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] 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] Dica

"/var/run/utmp", "/var/log/wtmp", e "/var/run/utmp" detém tal informação do utilizador. Veja login(1) e utmp(5).

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, I:92 908 Utilitários PCI do Linux: lspci(8)
usbutils * V:38, I:97 604 Utilitários USB do Linux: lsusb(8)
pcmciautils * V:0.8, I:13 100 Utilitários PCMCIA par Linux 2.6: pccardctl(8)
scsitools * V:0.18, I:1.1 484 colecção de ferramentas para gestão de hardware SCSI: lsscsi(8)
pnputils * V:0.01, I:0.16 108 Utilitários Plug and Play da BIOS: lspnp(8)
procinfo * V:0.3, I:3 164 informação do sistema obtida de "/proc": lsdev(8)
lshw * V:1.2, I:7 604 informação acerca da configuração do hardware: lshw(1)
discover * V:2, I:15 120 sistema de identificação de hardware: discover(8)

9.6.4. Configuração do hardware

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, I:49 1668 Hardware Abstraction Layer: lshal(1)
console-tools * V:47, I:84 956 Linux console font and keytable utilities
x11-xserver-utils * V:34, I:51 544 Utilitários do servido X: xset(1), xmodmap(1)
acpid * V:51, I:91 208 daemon to manage events delivered by the Advanced Configuration and Power Interface (ACPI)
acpi * V:4, I:35 92 utilitário para mostrar informação em dispositivos ACPI
apmd * V:1.2, I:11 252 daemon para gerir eventos entregues pelo Advanced Power Management (APM)
noflushd * V:0.04, I:0.09 248 daemon que permite que discos rijos inactivos parem o motor
sleepd * V:0.07, I:0.09 148 daemon para colocar um portátil em modo de adormecimento durante a inactividade
hdparm * V:11, I:38 304 hard disk access optimization (see Secção 9.3.7, “Optimização do disco rijo”)
smartmontools * V:7, I:23 1076 control and monitor storage systems using S.M.A.R.T.
setserial * V:1.5, I:3 180 colecção de ferramentas para gestão de portas série
memtest86+ * V:0.5, I:5 652 colecção de ferramentas para gestão de hardware de memória
scsitools * V:0.18, I:1.1 484 collection of tools for SCSI hardware management
tpconfig * V:0.3, I:0.5 220 utilitário para configurar dispositivos touchpad
setcd * V:0.06, I:0.3 28 optimização de acesso a 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] Dica

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.

[Dica] Dica

ntptrace(8) in the ntp package can trace a chain of NTP servers back to the primary source.

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 you have very new sound hardware, udev infrastructure should configure your sound system.

[Dica] Dica

Use "cat /dev/urandom > /dev/audio" or speaker-test(1) to test speaker. (^C to stop)

[Dica] 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, I:49 132 pacote base para sistemas de som ALSA e OSS
alsa-base * V:2, I:48 500 ficheiros de configuração da driver ALSA
alsa-utils * V:34, I:48 1984 utilitários para configurar e utilizar ALSA
oss-compat * V:28, I:33 60 compatibilidade de OSS sob ALSA para prevenir erros de "/dev/dsp não encontrado"
esound-common * V:19, I:56 232 Enlightened Sound Daemon (ESD) common (Enlightenment and GNOME)
esound * V:0.6, I:6 80 Enlightened Sound Daemon (ESD) server (Enlightenment and GNOME)
esound-clients * V:7, I:20 188 Enlightened Sound Daemon (ESD) client (Enlightenment and GNOME)
libesd0 * V:32, I:55 84 Enlightened Sound Daemon (ESD) library (Enlightenment and GNOME)
arts * I:7 40 servidor aRts (KDE)
libarts1c2a * V:13, I:23 5968 biblioteca aRts (KDE)
libartsc0 * V:10, I:32 48 biblioteca aRts (KDE)
jackd * V:0.8, I:3 32 JACK Audio Connection Kit. (JACK) server (low latency)
libjack0 * V:1.3, I:33 164 JACK Audio Connection Kit. (JACK) library (low latency)
nas * V:0.14, I:0.2 328 Network Audio System (NAS) server
libaudio2 * V:26, I:46 200 Network Audio System (NAS) library
pulseaudio * V:3, I:5 4052 servidor PulseAudio, substituto para o ESD
libpulse0 * V:15, I:36 792 biblioteca cliente PulseAudio, substituto para o ESD
libgstreamer0.10-0 * V:30, I:51 3368 GStreamer: motor de som do GNOME
libxine1 * V:5, I:27 36 xine: antigo motor de som do KDE
libphonon4 * I:16 572 Phonon: novo motor de som do KDE

There is usually a common sound engine for each popular desktop environment. Each sound engine used by the application can choose to connect to different sound servers.

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 écran

ambiente comando
A consola do Linux setterm -powersave off
O X Window (desactivar o protector de écran) xset s off
O X Window (desactivar o dpms) xset -dpms
O X Window (GUI de configuração do protector de écran) xscreensaver-command -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).

$ 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] 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.

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.

Tabela 9.21. Lista de ferramentas para segurança do sistema e verificação de integridade

pacote popcon tamanho descrição
logcheck * V:3, I:3 152 daemon to mail anomalies in the system logfiles to the administrator
debsums * V:2, I:3 320 utilitário para verifica pacotes instalados contra sumários de verificação MD5
chkrootkit * V:2, I:6 808 detector de rootkit
clamav * V:2, I:11 616 anti-virus utility for Unix - command-line interface
tiger * V:0.8, I:1.0 3148 relatar vulnerabilidades de segurança do sistema
tripwire * V:0.6, I:0.7 9456 verificador de integridade de ficheiros e directórios
john * V:0.7, I:2 532 active password cracking tool
aide * V:0.2, I:0.4 1213 Advanced Intrusion Detection Environment - static binary
bastille * V:0.12, I:0.4 1960 security hardening tool
integrit * V:0.08, I:0.16 440 programa de verificação de integridade de ficheiros
crack * V:0.03, I:0.2 204 programa de adivinhação de palavra-passe

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] 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

There are few notable features on Linux kernel 2.6 compared to 2.4.

  • Devices are created by the udev system (see 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

Many Linux features are configurable via kernel parameters as follows.

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] Nota

For compiling some kernel-specific programs such as the kernel modules from the external source and the automounter daemon (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

Debian has its own method of compiling the kernel and related modules.

Tabela 9.22. List of key packages to be installed for the kernel recompilation on the Debian system

pacote popcon tamanho descrição
build-essential * I:47 48 essential packages for building Debian packages: make, gcc, …
bzip2 * V:51, I:79 132 compress and decompress utilities for bz2 files
libncurses5-dev * V:4, I:25 6900 developer's libraries and docs for ncurses
git * V:5, I:17 10632 git: distributed revision control system used by the Linux kernel
fakeroot * V:4, I:32 444 provide fakeroot environment for building package as non-root
initramfs-tools * V:49, I:98 468 tool to build an initramfs (Debian specific)
kernel-package * V:1.5, I:14 2316 tool to build Linux kernel packages (Debian specific)
module-assistant * V:2, I:18 568 tool to help build module packages (Debian specific)
dkms * V:6, I:9 468 dynamic kernel module support (DKMS) (generic)
devscripts * V:2, I:11 1696 helper scripts for a Debian Package maintainer (Debian specific)
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] 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] 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] Nota

The dynamic kernel module support (DKMS) is a new distribution independent framework designed to allow individual kernel 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".

[Cuidado] 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 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 Winmodem, on your system.

Verificar recursos pertinentes.

9.8. Sistema virtualizado

Use of virtualized system enables us to run multiple instances of system simultaneously on a single hardware.

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

pacote popcon tamanho descrição
schroot * V:1.0, I:1.6 2460 ferramenta especializada para executar pacotes binários Debian em chroot
sbuild * V:0.11, I:0.3 428 ferramenta para construir pacotes binários Debian a partir de fontes Debian
pbuilder * V:0.5, I:2 1192 construtor de pacotes pessoais para pacotes Debian
debootstrap * V:1.6, I:12 268 bootstrap a basic Debian system (written in sh)
cdebootstrap * V:0.3, I:2 116 bootstrap a Debian system (written in C)
rootstrap * V:0.02, I:0.17 156 ferramenta para construir imagens de sistema de ficheiros de Linux completas
virt-manager * V:0.5, I:1.6 5908 Virtual Machine Manager: aplicação de ambiente de trabalho para gerir máquinas virtuais
libvirt-bin * V:1.4, I:2 2240 programas para a biblioteca libvirt
user-mode-linux * V:0.07, I:0.3 20540 Modo-de-utilizador Linux (kernel)
bochs * V:0.05, I:0.3 3280 Bochs: emulador PC IA-32
qemu * V:0.6, I:6 460 QEMU: emulador de processador genérico rápido
qemu-system * V:2, I:3 38196 QEMU: binários de emulação de sistema completo
qemu-user * V:0.3, I:3 16716 QEMU: binários de emulação em modo de utilizador
qemu-utils * V:0.4, I:3 756 QEMU: utilitários
qemu-kvm * V:1.3, I:2 4308 KVM: full virtualization on x86 hardware with the hardware-assisted virtualization
virtualbox-ose * V:2, I:4 31728 VirtualBox: x86 virtualization solution on i386 and amd64
xen-tools * V:0.2, I:1.9 1236 ferramentas para gerir o servidor virtual XEN da debian
wine * V:1.7, I:13 96 Wine: Windows API Implementation (standard suite)
dosbox * V:0.5, I:2 2460 DOSBox: x86 emulator with Tandy/Herc/CGA/EGA/VGA/SVGA graphics, sound and DOS
dosemu * V:0.2, I:1.2 5940 DOSEMU: O Emulador de DOS do Linux
vzctl * V:0.7, I:1.1 1056 OpenVZ server virtualization solution - control tools
vzquota * V:0.7, I:1.2 204 OpenVZ server virtualization solution - quota tools
lxc * V:0.05, I:0.2 744 Linux containers user space 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] Nota

Some functionalities described here are only available in squeeze.

[Nota] Nota

Default Debian kernels support KVM since lenny.

Typical work flow for virtualization involves several steps.

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

For other virtual disk image files, you can use qemu-nbd(8) to export them using network block device protocol and mount them using the nbd kernel module.

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 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] Dica

You may export only the first partition of "disk.img" using "-P 1" option to 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] Cuidado

Os exemplos em baixo assumem que ambos os sistemas pai e chroot partilham a mesma arquitectura de CPU.

You can learn how to setup and use chroot(8) by running pbuilder(8) program under script(1) as follows.

$ sudo mkdir /sid-root
$ sudo pbuilder --create --no-targz --debug --buildplace /sid-root

You see how debootstrap(8) or cdebootstrap(1) populate system data for sid environment under "/sid-root".

[Dica] Dica

These debootstrap(8) or cdebootstrap(1) are used to install Debian by the Debian Installer. These can also be used to install Debian to a system without using a Debian install disk, but instead from another GNU/Linux distribution.

$ sudo pbuilder --login --no-targz  --debug --buildplace /sid-root

You see how a system shell running under sid environment is created as the following.

  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. Run "chroot /sid-root bin/bash -c 'exec -a -bash bin/bash'"
[Nota] Nota

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