Visual guide

Linux, from user to firewall.

A visual, exam-style guide: users and root, permissions, processes, the file tree, commands, networking, SSH, firewalls, health tools and cleaning your history.

O que é o LinuxWhat Linux is

Linux é, em sentido estrito, só o kernel (o núcleo): o programa que fala com o hardware e reparte CPU, memória, disco e rede entre os outros programas. Tudo o que você usa no terminal (shell, ls, grep, ssh) são programas comuns que pedem coisas ao kernel. A combinação kernel + ferramentas + gerenciador de pacotes é uma distribuição (Ubuntu, Debian, Fedora, Arch).Strictly speaking, Linux is just the kernel: the program that talks to the hardware and shares CPU, memory, disk and network among the other programs. Everything you use in the terminal (shell, ls, grep, ssh) is an ordinary program that asks the kernel for things. Kernel + tools + package manager is a distribution (Ubuntu, Debian, Fedora, Arch).

Dois princípios explicam quase tudo nesta nota: “tudo é arquivo” (discos, terminais, processos e até a rede aparecem como arquivos ou descritores de arquivo) e “todo programa roda como algum usuário” (as permissões decidem o que ele pode tocar). Aprenda esses dois e o resto vira consequência.Two principles explain almost everything in this note: “everything is a file” (disks, terminals, processes and even the network show up as files or file descriptors) and “every program runs as some user” (permissions decide what it may touch). Learn these two and the rest follows.

AplicaçõesApplications firefox · vim · ssh · python · docker Shell e utilitáriosShell and utilities bash · zsh · ls · cp · grep · systemctl BibliotecasLibraries glibc (libc): traduz funções em chamadas ao kernel espaço douser usuáriospace chamadas de sistema (syscalls): open, read, write, fork, socket…system calls (syscalls): open, read, write, fork, socket… ProcessosProcesses MemóriaMemory ArquivosFiles RedeNetwork Drivers kernel Hardware: CPU · RAM · disco · placa de redeHardware: CPU · RAM · disk · network card
As camadas do Linux. Programas nunca tocam o hardware: pedem ao kernel por syscalls, e o kernel decide se permite.The Linux layers. Programs never touch the hardware: they ask the kernel through syscalls, and the kernel decides whether to allow it.

Livros e fontes recomendadosRecommended books and sources

FonteSourceUse paraUse it for
The Linux Programming Interface, Michael Kerrisk (No Starch, 2010)A referência definitiva: o que cada syscall faz de verdade. Cap. 8–9 usuários e credenciais, 15 atributos de arquivo, 17 ACLs, 24–27 processos, 56–61 sockets.The definitive reference: what each syscall really does. Ch. 8–9 users and credentials, 15 file attributes, 17 ACLs, 24–27 processes, 56–61 sockets.
How Linux Works, Brian Ward (No Starch, 3ª ed. 2021)A melhor ponte entre “usar” e “entender”: boot, kernel, disco, rede, serviços.The best bridge between “using” and “understanding”: boot, kernel, disk, network, services.
UNIX and Linux System Administration Handbook, Nemeth et al. (5ª ed.)Administração do dia a dia: contas, armazenamento, rede, segurança, monitoramento.Day-to-day administration: accounts, storage, networking, security, monitoring.
Operating Systems: Three Easy Pieces (OSTEP), Arpaci-DusseauTeoria gratuita e muito clara: processos, escalonamento, memória virtual, arquivos.Free and very clear theory: processes, scheduling, virtual memory, files.
Páginas man (man7.org) e Filesystem Hierarchy StandardThe man pages (man7.org) and the Filesystem Hierarchy StandardTexto oficial: man 7 hier, man 5 passwd, man 7 signal, man 7 capabilities.The official text: man 7 hier, man 5 passwd, man 7 signal, man 7 capabilities.
Guias de certificação: Linux Essentials e LPIC-1 (LPI), RHCSA (Red Hat)Certification guides: Linux Essentials and LPIC-1 (LPI), RHCSA (Red Hat)Listas de tópicos de prova; esta nota cobre o núcleo de todos eles.Exam topic lists; this note covers the core of all of them.
Estratégia de estudo: leia a seção, rode os comandos numa máquina virtual ou num contêiner descartável e só então faça as questões de prova no fim. Em Linux, ler sem digitar não fixa nada.Study strategy: read the section, run the commands in a throwaway virtual machine or container, and only then do the exam questions at the end. In Linux, reading without typing does not stick.

Usuários, grupos e superusuárioUsers, groups and the superuser

Para o kernel, um usuário é só um número: o UID. Nomes como “ana” existem para humanos; o kernel compara números. Cada usuário tem também um GID principal e pode pertencer a outros grupos. Os dados ficam em arquivos de texto em /etc.To the kernel a user is just a number: the UID. Names like “ana” exist for humans; the kernel compares numbers. Each user also has a primary GID and may belong to other groups. The data lives in plain text files in /etc.

/etc/passwd ana nomelogin x senhapassword 1000 UID 1000 GID Ana Silva comentáriocomment /home/ana diretóriohome /bin/bash shell O “x” diz: o hash da senha está em /etc/shadow, legível só pelo root.The “x” means: the password hash is in /etc/shadow, readable only by root. Campos separados por “:”. UID 0 = superusuário; 1–999 = contas de sistema; 1000+ = pessoas.Fields separated by “:”. UID 0 = superuser; 1–999 = system accounts; 1000+ = people.
Uma linha de /etc/passwd tem sete campos. É o “cadastro” de cada usuário.One line of /etc/passwd has seven fields. It is each user’s “registration”.
ArquivoFileGuardaHoldsQuem lêWho can read
/etc/passwdcontas: nome, UID, GID, home, shellaccounts: name, UID, GID, home, shelltodoseveryone
/etc/shadowhash da senha, validade, bloqueiopassword hash, expiry, locksó rootroot only
/etc/groupgrupos e seus membrosgroups and their memberstodoseveryone
/etc/sudoers e /etc/sudoers.d/quem pode virar quem (editar só com visudo)who may become whom (edit only with visudo)só rootroot only

O superusuário (root)The superuser (root)

O superusuário é quem tem UID 0, não quem se chama “root”. Para o kernel, UID 0 ignora as checagens de permissão de arquivos e pode, por exemplo, ler qualquer arquivo, matar qualquer processo e abrir portas abaixo de 1024. No Linux moderno esse poder é dividido em capabilities (ex.: CAP_NET_BIND_SERVICE só para abrir portas baixas), mas o root tradicional tem todas. Por isso a regra de ouro é: use root só no instante em que precisar.The superuser is whoever has UID 0, not whoever is named “root”. To the kernel, UID 0 skips file permission checks and can, for example, read any file, kill any process and bind ports below 1024. Modern Linux splits that power into capabilities (e.g. CAP_NET_BIND_SERVICE just for low ports), but the traditional root has them all. Hence the golden rule: use root only at the moment you need it.

ana (UID 1000) usuário comumregular user sudo apt update pede ao sudoasks sudo sudoers? pede senha de anaasks ana’s password root (UID 0) 1 comando1 command Tudo fica registrado: /var/log/auth.log (Debian/Ubuntu) ou journalctl _COMM=sudo.Everything is logged: /var/log/auth.log (Debian/Ubuntu) or journalctl _COMM=sudo.
O fluxo do sudo: a pessoa continua sendo ela mesma, e só aquele comando roda como root. Isso deixa um rastro de auditoria, ao contrário de um shell root permanente.The sudo flow: the person stays themselves, and only that command runs as root. That leaves an audit trail, unlike a permanent root shell.
id                         # uid=1000(ana) gid=1000(ana) groups=1000(ana),27(sudo),1001(dev)
whoami                     # ana
groups ana                 # grupos de ana
getent passwd ana          # a linha de ana (funciona com LDAP também)

sudo useradd -m -s /bin/bash -G sudo ana   # cria usuário + home + shell + grupo extra
sudo passwd ana                            # define a senha
sudo usermod -aG dev ana                   # ADICIONA ao grupo dev (sem -a, apaga os outros!)
sudo groupadd dev                          # cria grupo
sudo gpasswd -d ana dev                    # tira ana do grupo dev
sudo passwd -l ana                         # bloqueia a conta (-u desbloqueia)
sudo userdel -r ana                        # remove usuário e o home

su - ana                   # vira ana (pede a senha DE ANA); o "-" carrega o ambiente dela
sudo -i                    # shell de root, autenticando com a SUA senha
sudo -l                    # lista o que você pode rodar com sudo
sudo visudo                # edita o sudoers com validação de sintaxe
Pegadinha clássica: usermod -G dev ana (sem -a) substitui todos os grupos suplementares de ana, inclusive o sudo. Use sempre -aG. E quem muda de grupo precisa abrir uma nova sessão (logout/login ou newgrp) para o grupo valer.Classic trap: usermod -G dev ana (without -a) replaces all of ana’s supplementary groups, including sudo. Always use -aG. And someone whose groups changed needs a new session (log out/in or newgrp) for it to take effect.
No Debian/Ubuntu existe também adduser, mais amigável (pergunta nome e senha). useradd é o comando de baixo nível, igual em todas as distribuições. Para a teoria de UID real, efetivo e salvo, veja o cap. 9 do Kerrisk.Debian/Ubuntu also have adduser, friendlier (it asks name and password). useradd is the low-level command, the same on every distribution. For the theory of real, effective and saved UIDs, see Kerrisk ch. 9.

Arquivos e permissõesFiles and permissions

Todo arquivo tem um dono (usuário), um grupo e nove bits de permissão: leitura (r), escrita (w) e execução (x) para três públicos: o dono (u), o grupo (g) e todo o resto (o). O kernel escolhe um público, nesta ordem: se você é o dono, vale só a regra do dono; senão, se está no grupo, vale a do grupo; senão, a de outros.Every file has an owner (user), a group and nine permission bits: read (r), write (w) and execute (x) for three audiences: the owner (u), the group (g) and everybody else (o). The kernel picks one audience, in this order: if you are the owner, only the owner rule applies; otherwise, if you are in the group, the group rule; otherwise, the others rule.

ls -l: - r w x r - x r - - 1 ana dev 812 build.sh tipotype dono (u)owner (u) grupo (g)group (g) outros (o)others (o) rwx = 4+2+1 = 7 r-x = 4+0+1 = 5 r-- = 4+0+0 = 4 chmod 754 build.sh ← 7 (dono) 5 (grupo) 4 (outros)chmod 754 build.sh ← 7 (owner) 5 (group) 4 (others) tipo: - arquivo · d diretório · l link simbólico · c/b dispositivo · s socket · p fifotype: - file · d directory · l symlink · c/b device · s socket · p fifo
Lendo -rwxr-xr--: tipo, depois três trios. Em octal, r vale 4, w vale 2 e x vale 1; somam-se por público.Reading -rwxr-xr--: type, then three triplets. In octal, r is 4, w is 2 and x is 1; add them per audience.

O que r, w e x significam em cada tipoWhat r, w and x mean for each type

BitBitEm arquivoOn a fileEm diretórioOn a directory
rler o conteúdoread the contentlistar os nomes (ls)list the names (ls)
walterar o conteúdochange the contentcriar, renomear e apagar entradas dentro delecreate, rename and delete entries inside it
xexecutar como programarun as a program“atravessar”: entrar com cd e acessar arquivos pelo nome“traverse”: cd into it and reach files by name
Pegadinha: apagar um arquivo depende da permissão w do diretório, não do arquivo. Quem pode escrever no diretório pode apagar arquivos de outros dentro dele, a não ser que o sticky bit (abaixo) esteja ligado.Trap: deleting a file depends on the w permission of the directory, not of the file. Whoever can write to the directory can delete other people’s files inside it, unless the sticky bit (below) is on.
ls -l arquivo               # permissões, dono, grupo, tamanho, data
ls -ld /etc /tmp            # -d: o próprio diretório, não o conteúdo
stat arquivo                # tudo, inclusive inode e octal
namei -l /var/www/index.html   # mostra a permissão de CADA pedaço do caminho

chmod u+x script.sh         # simbólico: dono ganha x
chmod g-w,o-rwx arquivo     # grupo perde w; outros perdem tudo
chmod 640 arquivo           # octal: rw- r-- ---
chmod -R 755 pasta/         # recursivo (cuidado: põe x em arquivos também)
chmod a+r arquivo           # a = all (u+g+o)

sudo chown ana arquivo      # muda dono
sudo chown ana:dev arquivo  # dono e grupo de uma vez
sudo chown -R ana: pasta/   # "ana:" = grupo principal de ana
chgrp dev arquivo           # muda só o grupo (se você pertence a ele)

umask                       # máscara atual (típico 0022)
umask 027                   # novos arquivos: 640, novos diretórios: 750

A umask é subtraída das permissões-padrão (666 para arquivos, 777 para diretórios). Com umask 022: arquivos viram 644 e diretórios 755. Com 027: 640 e 750, ou seja, “outros” não veem nada.The umask is subtracted from the default permissions (666 for files, 777 for directories). With umask 022: files become 644 and directories 755. With 027: 640 and 750, meaning “others” see nothing.

Bits especiais: setuid, setgid e stickySpecial bits: setuid, setgid and sticky

BitBitOctalOctalEfeitoEffectExemplo realReal example
setuid (s no dono)4000o programa roda com os privilégios do dono do arquivothe program runs with the privileges of the file’s owner/usr/bin/passwd (dono root) altera /etc/shadow para um usuário comum/usr/bin/passwd (owner root) edits /etc/shadow for a regular user
setgid (s no grupo)2000em arquivo: roda com o grupo do arquivo. Em diretório: novos arquivos herdam o grupo do diretórioon a file: runs with the file’s group. On a directory: new files inherit the directory’s grouppasta compartilhada de um time: chmod g+s /srv/projetoa team’s shared folder: chmod g+s /srv/projeto
sticky (t em outros)1000em diretório: só o dono do arquivo (ou root) apaga ou renomeiaon a directory: only the file’s owner (or root) can delete or rename/tmp tem drwxrwxrwt/tmp is drwxrwxrwt
chmod 4755 programa         # setuid + rwxr-xr-x
chmod g+s /srv/projeto      # setgid no diretório
chmod +t /srv/publico       # sticky
find / -perm -4000 -type f 2>/dev/null   # AUDITORIA: lista todos os programas setuid
Segurança: programas setuid de root são alvo preferido de ataque; qualquer bug neles vira escalada de privilégio. Audite a lista com o find acima e desconfie de itens que você não reconhece.Security: setuid-root programs are a favourite attack target; any bug in them becomes privilege escalation. Audit the list with the find above and distrust entries you do not recognise.

ACLs: quando três públicos não bastamACLs: when three audiences are not enough

Se você precisa dar acesso a uma pessoa específica sem mexer no dono nem no grupo, use ACL (Access Control List; Kerrisk, cap. 17). O ls -l mostra um + no fim das permissões quando existe ACL.If you need to give access to one specific person without touching owner or group, use an ACL (Access Control List; Kerrisk, ch. 17). ls -l shows a + after the permissions when an ACL exists.

setfacl -m u:bia:rw relatorio.txt     # dá rw à usuária bia
setfacl -x u:bia relatorio.txt        # remove a regra
getfacl relatorio.txt                 # mostra todas

Estrutura de arquivosFile structure

O Linux tem uma única árvore de diretórios que começa em / (a raiz). Não existe “C:” ou “D:”: um pendrive ou outro disco é montado em algum diretório (por exemplo /mnt/usb) e seu conteúdo aparece ali. O Filesystem Hierarchy Standard (FHS) define o papel de cada diretório, e man 7 hier resume.Linux has one single tree of directories that starts at / (the root). There is no “C:” or “D:”: a USB stick or another disk is mounted on some directory (for example /mnt/usb) and its content appears there. The Filesystem Hierarchy Standard (FHS) defines each directory’s role, and man 7 hier summarises it.

/ /bin /sbin /lib comandos e bibliotecas essenciais (hoje links para /usr/…)essential commands and libraries (today links to /usr/…) /boot kernel e bootloader (GRUB)kernel and bootloader (GRUB) /dev dispositivos como arquivos: /dev/sda, /dev/null, /dev/ttydevices as files: /dev/sda, /dev/null, /dev/tty /etc configuração do sistema, em textosystem configuration, in text /home pastas dos usuários (/home/ana)users’ folders (/home/ana) /root home do superusuário (fora de /home)superuser’s home (outside /home) /media /mnt pontos de montagem de mídias e discosmount points for media and disks /opt software de terceiros em bloco (ex.: /opt/google)self-contained third-party software (e.g. /opt/google) /proc janela virtual para o kernel e os processos: /proc/PID, /proc/cpuinfovirtual window into the kernel and processes: /proc/PID, /proc/cpuinfo /sys dispositivos e drivers, também virtualdevices and drivers, also virtual /run estado de execução desde o boot (PIDs, sockets); some ao reiniciarruntime state since boot (PIDs, sockets); gone on reboot /srv dados servidos pela máquina (sites, FTP)data served by the machine (sites, FTP) /tmp temporários de todos (sticky bit); limpo no boot ou periodicamenteeveryone’s temporaries (sticky bit); cleaned at boot or periodically /usr programas, bibliotecas e docs instalados (bin, lib, share, local)installed programs, libraries and docs (bin, lib, share, local) /var dados que mudam: logs (/var/log), filas, caches, bancosdata that changes: logs (/var/log), queues, caches, databases
O mapa do sistema de arquivos. Memorize os quatro mais cobrados em prova: /etc (configuração), /var (dados variáveis e logs), /home (usuários) e /proc (kernel em tempo real).The filesystem map. Memorise the four most asked in exams: /etc (configuration), /var (variable data and logs), /home (users) and /proc (live kernel).

Montagem, discos e inodesMounting, disks and inodes

Cada arquivo é, por baixo, um inode: um registro com dono, permissões, tamanhos e ponteiros para os blocos de dados. O nome do arquivo vive no diretório, que é só uma tabela “nome → número do inode”. Por isso um arquivo pode ter vários nomes (hard links) e por isso renomear é instantâneo (Kerrisk, cap. 14 e 18).Underneath, each file is an inode: a record with owner, permissions, sizes and pointers to the data blocks. The file’s name lives in the directory, which is just a “name → inode number” table. That is why a file can have several names (hard links) and why renaming is instant (Kerrisk, ch. 14 and 18).

Tipo de linkLink typeO que éWhat it isComandoCommand
Hard linkHard linkoutro nome para o mesmo inode; o dado só some quando o último nome some; não cruza partiçõesanother name for the same inode; the data only goes when the last name goes; cannot cross partitionsln original apelido
Link simbólicoSymbolic linkum arquivo pequeno que guarda um caminho; quebra se o alvo some; pode cruzar partiçõesa small file that stores a path; breaks if the target disappears; can cross partitionsln -s alvo atalho
lsblk                       # discos e partições em árvore
df -h                       # espaço livre por sistema de arquivos
du -sh * | sort -h          # quem está ocupando espaço aqui
findmnt                     # o que está montado onde
sudo mount /dev/sdb1 /mnt/usb
sudo umount /mnt/usb        # (é umount, sem "n")
cat /etc/fstab              # o que monta automaticamente no boot
ls -i arquivo               # número do inode

Comandos do dia a diaEveryday commands

Todo comando segue o mesmo molde: comando [opções] [argumentos]. As opções curtas (-l) podem ser juntadas (-la); as longas usam dois traços (--all). Quando em dúvida, man comando, comando --help ou tldr comando (exemplos curtos).Every command follows the same mould: command [options] [arguments]. Short options (-l) can be combined (-la); long ones use two dashes (--all). When in doubt, man command, command --help or tldr command (short examples).

Navegar e olharMove around and look

ComandoCommandFazDoes
pwdmostra onde você estáshows where you are
ls -lahlista com detalhes (l), ocultos (a) e tamanhos legíveis (h)lists with details (l), hidden files (a) and human sizes (h)
cd /etc · cd .. · cd ~ · cd -entra · sobe · vai ao home · volta ao anteriorenter · up · go home · back to the previous
tree -L 2árvore até 2 níveis (pacote tree)tree two levels deep (package tree)
cat · less · head -n 20 · tail -fver tudo · paginar · primeiras linhas · seguir um log ao vivoview all · page through · first lines · follow a log live
file x · stat x · du -sh xtipo · detalhes · tamanhotype · details · size

Criar, copiar, mover e removerCreate, copy, move and remove

mkdir projeto                  # cria pasta
mkdir -p a/b/c                 # cria o caminho inteiro (-p = parents)
touch notas.txt                # cria arquivo vazio (ou atualiza a data)
echo "oi" > notas.txt          # cria/sobrescreve com conteúdo
echo "mais" >> notas.txt       # acrescenta ao fim

cp origem destino              # copia arquivo
cp -r pasta/ copia/            # copia pasta (-r = recursivo)
mv antigo novo                 # renomeia OU move (mesmo comando)
mv *.log /tmp/                 # move vários

rm arquivo                     # remove (NÃO vai para a lixeira!)
rm -r pasta/                   # remove pasta e conteúdo
rm -i arquivo                  # pergunta antes
rmdir pasta_vazia              # só remove se estiver vazia
Não existe “desfazer” no rm. Nunca rode rm -rf com variável não conferida (rm -rf "$DIR/" com DIR vazio vira rm -rf /). Em dúvida, liste primeiro com ls usando exatamente o mesmo padrão, ou instale trash-cli e use trash arquivo.There is no “undo” for rm. Never run rm -rf with an unchecked variable (rm -rf "$DIR/" with an empty DIR becomes rm -rf /). When in doubt, list first with ls using exactly the same pattern, or install trash-cli and use trash file.

Buscar e processar textoSearch and process text

find /var/log -name "*.log" -mtime -1     # logs alterados nas últimas 24 h
find . -type f -size +100M                # arquivos grandes
find . -user ana -perm -o+w               # de ana e graváveis por todos
grep -rn "erro" /var/log/ 2>/dev/null     # procura texto (-r recursivo, -n linha)
grep -i -E "fail|denied" auth.log         # sem diferenciar maiúsculas, regex
locate nome                               # busca rápida num índice (updatedb)
which python3 ; type cd                   # onde está / o que é um comando

sort | uniq -c | sort -rn | head          # o trio clássico: contar e ranquear
wc -l arquivo                             # conta linhas
cut -d: -f1 /etc/passwd                   # só o 1º campo (nomes de usuário)
awk '{print $1}' access.log               # 1ª coluna
sed -i 's/foo/bar/g' arquivo              # troca texto no arquivo

Pipes e redirecionamentoPipes and redirection

O poder do shell está em ligar programas pequenos. O | (pipe) liga a saída de um à entrada do outro. Cada processo nasce com três canais: 0 = entrada padrão (stdin), 1 = saída padrão (stdout), 2 = erros (stderr).The shell’s power lies in connecting small programs. The | (pipe) connects one’s output to another’s input. Each process is born with three channels: 0 = standard input (stdin), 1 = standard output (stdout), 2 = errors (stderr).

OperadorOperatorSignificaMeansExemploExample
>stdout para arquivo (sobrescreve)stdout to file (overwrites)ls > lista.txt
>>stdout para arquivo (acrescenta)stdout to file (appends)date >> log.txt
2>só os erroserrors onlyfind / 2>/dev/null
&>stdout e stderr juntosstdout and stderr togethermake &> build.log
<arquivo como stdinfile as stdinsort < nomes.txt
|saída de um vira entrada do outroone’s output becomes the other’s inputps aux | grep ssh
&& · || · ;só se deu certo · só se deu errado · sempreonly if it worked · only if it failed · alwaysmkdir x && cd x
sudo teeescrever em arquivo de root a partir de um pipewrite to a root-owned file from a pipeecho a | sudo tee /etc/x
Pegadinha: sudo echo a > /etc/x falha, porque o redirecionamento é feito pelo seu shell, que não é root; o sudo só vale para o echo. Use echo a | sudo tee /etc/x.Trap: sudo echo a > /etc/x fails, because the redirection is done by your shell, which is not root; sudo only applies to echo. Use echo a | sudo tee /etc/x.

Instalar, atualizar e gerenciar serviçosInstall, update and manage services

TarefaTaskDebian / UbuntuDebian / UbuntuFedora / RHELFedora / RHELArchArch
Atualizar índiceRefresh indexapt updatednf check-updatepacman -Sy
Atualizar tudoUpgrade allapt upgradednf upgradepacman -Syu
InstalarInstallapt install htopdnf install htoppacman -S htop
RemoverRemoveapt remove htopdnf remove htoppacman -R htop
BuscarSearchapt search xdnf search xpacman -Ss x
systemctl status ssh           # estado de um serviço (o nome pode ser sshd no Fedora)
sudo systemctl start|stop|restart ssh
sudo systemctl enable --now ssh    # liga no boot E agora
systemctl --failed             # o que falhou
journalctl -u ssh -f           # log do serviço ao vivo
journalctl -p err -b           # só erros desde o último boot

Processos, pais e filhosProcesses, parents and children

Um programa é um arquivo no disco; um processo é esse programa em execução, com seu PID (identificador), seu PPID (PID do pai), um dono (UID), memória própria, diretório atual e descritores de arquivos abertos. Em Linux todo processo tem um pai. A árvore começa no PID 1 (hoje, quase sempre o systemd), que o kernel inicia no boot.A program is a file on disk; a process is that program running, with its PID (identifier), its PPID (parent’s PID), an owner (UID), its own memory, a current directory and open file descriptors. In Linux every process has a parent. The tree starts at PID 1 (today almost always systemd), which the kernel launches at boot.

systemd PID 1 sshd PID 842 · :22 cron PID 901 sshd: ana PID 2210 bash PID 2215 vim PID 2301 ls PID 2320 seta = “criou” (fork)arrow = “created” (fork) Se o pai morre antes do filho, o filho é “adotado” pelo PID 1 (órfão).If the parent dies before the child, the child is “adopted” by PID 1 (orphan).
Uma sessão SSH vista como árvore: o systemd iniciou o sshd, que criou um processo para ana, que criou o bash, que criou vim e ls. Veja a sua com pstree -p.An SSH session seen as a tree: systemd started sshd, which created a process for ana, which created bash, which created vim and ls. See yours with pstree -p.

Como um processo nasce: fork, exec e waitHow a process is born: fork, exec and wait

Linux cria processos em duas etapas (Kerrisk, cap. 24–27). fork() clona o processo atual: nasce um filho idêntico, com PID novo. Em seguida o filho chama exec(), que troca o programa dentro dele (o PID continua). O pai chama wait() para esperar o filho terminar e ler o código de saída. É exatamente isso que o bash faz quando você digita ls.Linux creates processes in two steps (Kerrisk, ch. 24–27). fork() clones the current process: an identical child is born with a new PID. Then the child calls exec(), which swaps the program inside it (the PID stays). The parent calls wait() to wait for the child to finish and read its exit code. This is exactly what bash does when you type ls.

bash (pai)bash (parent) filhochild fork() PID novo, cópia do painew PID, copy of parent exec("ls") agora roda o lsnow runs ls wait() pai dorme esperandoparent sleeps, waiting exit(0) → SIGCHLD o pai lê o código de saída ($?) e o kernel libera o filhothe parent reads the exit code ($?) and the kernel frees the child
A dança fork → exec → exit → wait. Sem o wait() do pai, o filho terminado vira zumbi.The fork → exec → exit → wait dance. Without the parent’s wait(), the finished child becomes a zombie.
// fork_exec.c — gcc fork_exec.c -o fork_exec
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    pid_t pid = fork();                       // clona o processo
    if (pid == -1) { perror("fork"); exit(1); }

    if (pid == 0) {                           // aqui roda o FILHO
        execlp("ls", "ls", "-l", (char *)NULL);
        perror("execlp");                     // só chega aqui se o exec falhar
        _exit(127);
    }

    int status;                               // aqui roda o PAI
    waitpid(pid, &status, 0);                 // espera e "colhe" o filho
    printf("pai %d: filho %d saiu com %d\n", getpid(), pid, WEXITSTATUS(status));
    return 0;
}

Estados de um processoProcess states

novonew pronto (R)ready (R) executando (R)running (R) dormindo (S/D)sleeping (S/D) parado (T)stopped (T) zumbi (Z)zombie (Z) fork CPU espera I/Owaits for I/O evento chegouevent arrived Ctrl+Z exit zumbi: já terminou, mas o pai ainda não chamou wait(); só ocupa uma linha na tabela de processos.zombie: already finished, but the parent has not called wait() yet; it only takes a row in the process table. D = sono ininterruptível (esperando disco/rede); nem kill -9 mata até o I/O voltar.D = uninterruptible sleep (waiting on disk/network); not even kill -9 works until the I/O returns. SIGCONT (fg/bg) tira do estado parado.SIGCONT (fg/bg) takes it out of the stopped state.
O ciclo de vida. A coluna STAT do ps mostra a letra de cada estado.The lifecycle. The STAT column of ps shows each state’s letter.

Sinais: como falar com um processoSignals: how to talk to a process

SinalSignalNºNo.QuandoWhenPode ser tratado?Can be handled?
SIGINT2Ctrl+C: “interrompa”Ctrl+C: “interrupt”simyes
SIGTERM15kill PID (padrão): “termine com educação”kill PID (default): “please terminate”sim (permite limpar)yes (allows cleanup)
SIGKILL9kill -9: o kernel mata na horakill -9: the kernel kills at oncenãono
SIGHUP1terminal fechou; muitos daemons recarregam a configuraçãoterminal closed; many daemons reload configurationsimyes
SIGSTOP / SIGCONT19 / 18pausar / continuar (Ctrl+Z usa SIGTSTP)pause / continue (Ctrl+Z uses SIGTSTP)STOP nãoSTOP no
ps aux                          # todos os processos (user, PID, %CPU, %MEM, comando)
ps -eo pid,ppid,stat,user,cmd   # escolha as colunas: veja o PPID e o STAT
ps -ef --forest                 # a árvore em texto
pstree -p                       # a árvore, com PIDs
pgrep -a ssh                    # PIDs pelo nome
top        # ou htop / btop: ao vivo (q sai; k mata; M ordena por memória)

echo $$ ; echo $PPID            # PID do seu shell e do pai dele
bash -c 'echo eu=$$ pai=$PPID'  # um filho: o pai dele é o seu shell
cat /proc/$$/status | head      # o kernel descreve o processo como arquivo

kill 2301                       # SIGTERM (educado)
kill -9 2301                    # SIGKILL (último recurso)
kill -STOP 2301 ; kill -CONT 2301
pkill -f "python app.py"        # por padrão no comando
killall firefox                 # por nome

sleep 300 &                     # & = em segundo plano
jobs ; fg %1 ; bg %1            # lista; traz à frente; manda ao fundo
nohup ./job.sh &                # sobrevive ao fechar o terminal
nice -n 10 ./pesado.sh          # prioridade menor (-20 a 19; menor número = mais prioridade)
renice 5 -p 2301
Como lidar com um zumbi: ele já está morto, então kill não adianta. Descubra o pai (ps -o ppid= -p PID) e conserte ou reinicie o pai; quando o pai morre, o PID 1 adota e colhe os zumbis. Alguns zumbis passageiros são normais; milhares indicam um bug no pai.How to handle a zombie: it is already dead, so kill is useless. Find the parent (ps -o ppid= -p PID) and fix or restart the parent; when the parent dies, PID 1 adopts and reaps the zombies. A few passing zombies are normal; thousands point to a bug in the parent.

Load average (uptime, top) mostra a média de processos prontos para rodar ou esperando disco em 1, 5 e 15 minutos. Compare com o número de CPUs (nproc): em 4 CPUs, load 4 é “cheio” e 12 é sobrecarga.Load average (uptime, top) shows the average number of processes ready to run or waiting for disk over 1, 5 and 15 minutes. Compare it with the number of CPUs (nproc): on 4 CPUs, load 4 is “full” and 12 is overload.

Redes: ver, entender e interagirNetworking: see, understand and interact

Para a rede, o Linux usa a pilha TCP/IP no kernel. Quem fala com ela são os sockets (Kerrisk, cap. 56–61): um programa pede ao kernel um socket, liga-o a um IP e uma porta e passa a enviar e receber bytes. Uma conexão é identificada por quatro valores: IP e porta de origem, IP e porta de destino.For networking, Linux uses the TCP/IP stack inside the kernel. Programs talk to it through sockets (Kerrisk, ch. 56–61): a program asks the kernel for a socket, binds it to an IP and a port, and sends and receives bytes. A connection is identified by four values: source IP and port, destination IP and port.

camadalayer protocolosprotocols ferramentas para ver e interagirtools to inspect and interact AplicaçãoApplication HTTP · SSH · DNS · SMTP curl · ssh · dig · wget TransporteTransport TCP · UDP · portas ss · nc · nmap · lsof -i Internet IP · ICMP · rotas ip addr · ip route · ping · mtr EnlaceLink Ethernet · Wi-Fi · MAC · ARP ip link · ip neigh · iw · ethtool tcpdump e Wireshark capturam pacotes de todas as camadas ao mesmo tempo.tcpdump and Wireshark capture packets of all layers at once.
As quatro camadas do TCP/IP e a ferramenta certa para cada uma. Diagnostique de baixo para cima: cabo/Wi-Fi, IP, rota, DNS, porta, aplicação.The four TCP/IP layers and the right tool for each. Troubleshoot bottom-up: cable/Wi-Fi, IP, route, DNS, port, application.

Ver o que existe: interfaces, rotas e DNSSee what exists: interfaces, routes and DNS

ip -br addr                     # interfaces e IPs, uma linha cada (-br = brief)
ip route                        # tabela de rotas; "default via X" é o seu gateway
ip neigh                        # vizinhos na LAN (tabela ARP): quem está na minha rede
ip -s link                      # contadores de pacotes e erros por interface
nmcli device status             # estado (NetworkManager); nmtui = menu em texto
resolvectl status               # servidores DNS em uso (systemd-resolved)
cat /etc/hosts                  # nomes locais fixos

Ver o que está acontecendo: conexões e portasSee what is happening: connections and ports

ss -tulpn                       # QUEM ESTÁ ESCUTANDO: t=TCP u=UDP l=listen p=processo n=numérico
ss -tn state established        # conexões ativas agora
ss -tnp dst :443                # conexões saindo para a porta 443, com o processo
sudo lsof -i :8080              # que processo usa a porta 8080
sudo tcpdump -i any -n port 53  # pacotes DNS ao vivo (Ctrl+C para parar)
sudo tcpdump -i eth0 -w captura.pcap   # salva para abrir no Wireshark
sudo nethogs                    # banda por PROCESSO (apt install nethogs)
sudo iftop                      # banda por conexão

Como ler ss -tulpn: a coluna Local Address é a chave. 0.0.0.0:22 ou *:22 = aceita de qualquer lugar; 127.0.0.1:5432 = só deste computador (seguro); [::]:80 = o mesmo, mas em IPv6. Cada linha com endereço público é uma porta que um atacante pode tentar.How to read ss -tulpn: the Local Address column is the key. 0.0.0.0:22 or *:22 = accepts from anywhere; 127.0.0.1:5432 = this computer only (safe); [::]:80 = the same, but over IPv6. Every line with a public address is a port an attacker may try.

Interagir: testar, resolver nomes e falar HTTPInteract: test, resolve names and speak HTTP

ping -c 4 1.1.1.1               # chega? (testa IP, sem DNS)
ping -c 4 example.com           # se o IP funciona e este não, o problema é DNS
mtr example.com                 # traceroute + ping contínuo (apt install mtr-tiny)
traceroute example.com          # por quais roteadores o pacote passa

dig example.com +short          # resolve nome → IP
dig MX example.com              # registros de e-mail
curl -I https://example.com     # só os cabeçalhos HTTP
curl -v https://example.com     # tudo, inclusive o handshake TLS
curl -s https://api.exemplo.dev/health | jq .

nc -zv servidor 22              # a porta 22 está aberta? (z = só testa)
nc -l 9000                      # abre um "servidor" simples na porta 9000

Um roteiro de diagnósticoA troubleshooting script

  1. ip -br addr: a interface está UP e tem IP? Se não, o problema é cabo, Wi-Fi ou DHCP.ip -br addr: is the interface UP and does it have an IP? If not, it is the cable, Wi-Fi or DHCP.
  2. ip route e ping <gateway>: você alcança o roteador?ip route and ping <gateway>: can you reach the router?
  3. ping 1.1.1.1: sai para a internet?ping 1.1.1.1: does it reach the internet?
  4. dig example.com: o nome resolve? Se o passo 3 funciona e este não, é DNS.dig example.com: does the name resolve? If step 3 works and this does not, it is DNS.
  5. nc -zv host porta: a porta responde? Se não, firewall ou serviço parado.nc -zv host port: does the port answer? If not, firewall or stopped service.
  6. curl -v e os logs do serviço (journalctl -u): a aplicação responde direito?curl -v and the service logs (journalctl -u): does the application answer properly?

SSH: entrar, acompanhar e protegerSSH: log in, watch and protect

O SSH abre um terminal remoto cifrado (porta 22). É a porta de entrada de quase todo servidor Linux, então vale entender como funciona e como acompanhá-lo. O servidor prova quem é com uma chave de host; você prova quem é com senha ou, melhor, com um par de chaves: a privada nunca sai da sua máquina, a pública vai para o servidor.SSH opens an encrypted remote terminal (port 22). It is the front door of almost every Linux server, so it is worth understanding how it works and how to watch it. The server proves who it is with a host key; you prove who you are with a password or, better, a key pair: the private key never leaves your machine, the public one goes to the server.

Cliente (seu PC)Client (your PC) ~/.ssh/id_ed25519 sua chave PRIVADA (600)your PRIVATE key (600) ~/.ssh/known_hosts chaves de servidores já vistoskeys of servers already seen ~/.ssh/config apelidos: “ssh meuserver”aliases: “ssh myserver” ServidorServer /etc/ssh/sshd_config regras do servidorserver rules ~/.ssh/authorized_keys chaves PÚBLICAS aceitasaccepted PUBLIC keys /etc/ssh/ssh_host_*_key identidade do servidorserver identity TCP :22 1 chave do host1 host key 2 prova (assina)2 proof (signs) 3 canal cifrado3 encrypted channel
Os arquivos de cada lado. Na primeira conexão o cliente pergunta se confia na chave do host e a grava em known_hosts; se ela mudar depois, o SSH avisa (pode ser ataque).The files on each side. On first connection the client asks whether to trust the host key and stores it in known_hosts; if it changes later, SSH warns you (it may be an attack).
ssh-keygen -t ed25519 -C "ana@notebook"   # cria o par de chaves (defina uma passphrase)
ssh-copy-id ana@servidor                  # instala a pública no servidor
ssh ana@servidor                          # entra
ssh -v ana@servidor                       # diagnóstico: mostra cada etapa
ssh ana@servidor 'df -h'                  # roda um comando e sai
scp arquivo ana@servidor:/tmp/            # copia por SSH
rsync -avz --progress pasta/ ana@servidor:/backup/   # sincroniza (só o que mudou)
ssh -L 5432:localhost:5432 ana@servidor   # túnel: seu :5432 vira o banco do servidor
ssh -J bastion ana@interno                # salta por um bastion host
# ~/.ssh/config  ->  depois basta: ssh meuserver
Host meuserver
    HostName 203.0.113.10
    User ana
    IdentityFile ~/.ssh/id_ed25519

Quem está conectado e o que aconteceuWho is connected and what happened

who ; w                          # quem está logado agora e o que está executando
last -n 20                       # últimos logins
sudo lastb -n 20                 # tentativas de login que FALHARAM
ss -tnp state established '( sport = :22 )'   # sessões SSH abertas
sudo journalctl -u ssh --since "1 hour ago"   # log do sshd (Fedora: -u sshd)
sudo grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head

Endurecer o servidor SSHHardening the SSH server

Crie um arquivo em /etc/ssh/sshd_config.d/ (ou edite o sshd_config). Comentários ficam em linhas próprias.Create a file in /etc/ssh/sshd_config.d/ (or edit sshd_config). Comments go on their own lines.

# /etc/ssh/sshd_config.d/10-hardening.conf
# ninguém entra direto como root
PermitRootLogin no
# só chaves (copie a sua ANTES de ligar isto!)
PasswordAuthentication no
PubkeyAuthentication yes
# lista branca de usuários
AllowUsers ana bia
MaxAuthTries 3
sudo sshd -t                     # valida a sintaxe ANTES de aplicar
sudo systemctl reload ssh        # aplica sem derrubar as sessões atuais (Fedora: sshd)
Antes de desligar a senha, abra uma segunda sessão e confirme que entra com a chave. Se errar numa máquina remota, você se tranca para fora. O fail2ban complementa: bane por alguns minutos os IPs que erram muitas vezes.Before turning the password off, open a second session and confirm the key works. If you get it wrong on a remote machine, you lock yourself out. fail2ban complements this: it bans IPs that fail too many times for a few minutes.

Firewall: filtrar o que entraFirewall: filtering what comes in

Um firewall é um porteiro: olha cada pacote e decide deixar passar, descartar ou recusar. No Linux quem filtra é o netfilter, dentro do kernel. O que você usa são “controles” para ele: nftables (o moderno), iptables (o antigo, hoje muitas vezes um tradutor para nftables), e frentes simples como ufw (Ubuntu/Debian) e firewalld (Fedora/RHEL).A firewall is a doorman: it looks at each packet and decides to let it through, drop it or reject it. In Linux the filtering is done by netfilter, inside the kernel. What you use are “controls” for it: nftables (the modern one), iptables (the old one, today often a translator to nftables), and simple front ends such as ufw (Ubuntu/Debian) and firewalld (Fedora/RHEL).

pacote entrapacket in PREROUTING rota?route? FORWARD POSTROUTING INPUT processo locallocal process OUTPUT saiout é para mimfor me só passando (roteador)just passing (router) Cada gancho tem regras: ACCEPT (passa), DROP (descarta calado), REJECT (recusa avisando).Each hook has rules: ACCEPT (let through), DROP (discard silently), REJECT (refuse with notice). Um PC comum usa quase só INPUT e OUTPUT; FORWARD é de roteadores e hosts de contêineres.An ordinary PC mostly uses INPUT and OUTPUT; FORWARD is for routers and container hosts.
O caminho de um pacote pelos ganchos do netfilter. A regra mais importante de um computador pessoal está no INPUT: o que entra sem ter sido pedido.A packet’s path through the netfilter hooks. The most important rule on a personal computer is in INPUT: what comes in without having been asked for.

A política certa: negar por padrãoThe right policy: deny by default

A ideia de ouro: bloqueie tudo que entra, libere só o necessário. O que sai continua livre, e as respostas a conexões que você iniciou entram sozinhas (o firewall é stateful: lembra das conexões).The golden idea: block everything coming in, allow only what is needed. Outgoing traffic stays free, and replies to connections you started come in on their own (the firewall is stateful: it remembers connections).

# ufw (Ubuntu/Debian): o caminho mais simples
sudo ufw status verbose                  # está ativo? quais regras?
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp                    # LIBERE O SSH ANTES de ativar, se for remoto!
sudo ufw allow from 192.168.1.0/24 to any port 9090 proto tcp   # só a sua LAN
sudo ufw limit ssh                       # permite, mas freia força bruta
sudo ufw enable
sudo ufw status numbered ; sudo ufw delete 3   # listar e apagar uma regra

# firewalld (Fedora/RHEL)
sudo firewall-cmd --list-all
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
# /etc/nftables.conf
table inet filter {
  chain input {
    type filter hook input priority 0; policy drop;
    ct state established,related accept   # respostas ao que EU pedi
    ct state invalid drop
    iif "lo" accept                       # tráfego interno da máquina
    ip protocol icmp accept               # ping
    ip6 nexthdr icmpv6 accept
    tcp dport 22 accept                   # SSH
  }
  chain forward { type filter hook forward priority 0; policy drop; }
  chain output  { type filter hook output  priority 0; policy accept; }
}
sudo nft -f /etc/nftables.conf            # aplica o arquivo
sudo nft list ruleset                     # ver tudo o que está valendo
sudo systemctl enable --now nftables      # carrega no boot
Docker e ufw: o Docker mexe direto nas regras do netfilter, e portas publicadas com -p 8080:80 podem ficar abertas ao mundo mesmo com o ufw negando. Publique só em localhost (-p 127.0.0.1:8080:80) ou trate o assunto na cadeia DOCKER-USER.Docker and ufw: Docker edits the netfilter rules directly, and ports published with -p 8080:80 can be open to the world even when ufw denies them. Publish only on localhost (-p 127.0.0.1:8080:80) or handle it in the DOCKER-USER chain.

Proteger o computador e como saberProtecting the computer and how to know

Firewall é uma camada, não a defesa inteira. Segurança é defesa em profundidade: se uma camada falha, a próxima segura. A ordem prática é: reduzir o que está exposto, atualizar, limitar quem entra, vigiar e ter cópia de segurança.A firewall is one layer, not the whole defence. Security is defence in depth: if one layer fails, the next holds. The practical order is: reduce what is exposed, update, limit who gets in, watch, and keep backups.

RedeNetwork firewall · só portas necessárias · Wi-Fi/roteador seguros SistemaSystem atualizações · usuários e sudo · SSH só com chave · fail2ban ServiçosServices desligue o que não usa · ss -tulpn · sem root em serviços DadosData backup 3-2-1 · disco cifrado (LUKS) · permissões justas
Defesa em profundidade, de fora para dentro. O atacante precisa vencer todas as camadas; você só precisa que uma segure.Defence in depth, from the outside in. The attacker must beat every layer; you only need one to hold.

Como saber se o seu computador está protegidoHow to know whether your computer is protected

PerguntaQuestionComandoCommandResultado saudávelHealthy result
O que está escutando?What is listening?ss -tulpnsó o que você reconhece; o resto em 127.0.0.1only what you recognise; the rest on 127.0.0.1
O firewall está ativo?Is the firewall on?sudo ufw status verbose · sudo nft list rulesetStatus: active, política deny (incoming)Status: active, policy deny (incoming)
Como me veem de fora?How do others see me?nmap -sV IP-DA-MAQUINA (de OUTRO computador seu)só as portas que você liberouonly the ports you opened
Há atualizações pendentes?Any pending updates?apt list --upgradable · dnf check-updatevazio, ou só itens recentesempty, or only recent items
Alguém tentou entrar?Did anyone try to get in?sudo lastb | head · journalctl -u ssh -p warningpoucas falhas; sem sucesso desconhecido em lastfew failures; no unknown success in last
Quem tem poder de root?Who has root power?getent group sudo · awk -F: '$3==0' /etc/passwdsó quem deveria; só root com UID 0only who should; only root with UID 0
Há contas sem senha?Any accounts without a password?sudo awk -F: '$2==""' /etc/shadowsem saídano output
Existe uma auditoria pronta?Is there a ready-made audit?sudo lynis audit systemlista de avisos e sugestões, com nota finallist of warnings and suggestions with a final score
Só rode nmap, varreduras e testes de força bruta em máquinas e redes suas ou com autorização por escrito. Varrer redes alheias pode ser crime e costuma violar os termos de provedores.Only run nmap, scans and brute-force tests on machines and networks that are yours or with written authorisation. Scanning other people’s networks can be a crime and usually breaks provider terms.

Lista de verificação mínimaMinimum checklist

  1. Atualizações automáticas de segurança ligadas (unattended-upgrades no Debian/Ubuntu, dnf-automatic no Fedora).Automatic security updates on (unattended-upgrades on Debian/Ubuntu, dnf-automatic on Fedora).
  2. Firewall com política de negar entrada por padrão.Firewall with a deny-incoming default policy.
  3. Uso diário com usuário comum; sudo só quando preciso. Nunca navegar como root.Daily use with a regular user; sudo only when needed. Never browse as root.
  4. SSH (se existir) só com chave, sem login de root, com fail2ban.SSH (if it exists) key-only, no root login, with fail2ban.
  5. Serviços desnecessários desligados: systemctl disable --now nome.Unneeded services turned off: systemctl disable --now name.
  6. Senhas fortes e únicas em um gerenciador; disco cifrado (LUKS) em notebooks.Strong, unique passwords in a manager; encrypted disk (LUKS) on laptops.
  7. Backup 3-2-1 (3 cópias, 2 mídias, 1 fora do local) e teste de restauração.3-2-1 backup (3 copies, 2 media, 1 off-site) and a restore test.
  8. Instalar software só de repositórios oficiais ou fontes verificadas; ler antes de rodar curl … | sh.Install software only from official repositories or verified sources; read before running curl … | sh.

Ferramentas visuais: TUI e webVisual tools: TUI and web

Você não precisa decorar tudo: existem interfaces de terminal (TUI) e web que mostram saúde do sistema, logs, SSH, Git e contêineres de forma visual. As “lazy” (lazygit, lazydocker…) seguem a ideia de resumir dezenas de comandos em atalhos de teclado. Todas abaixo são projetos abertos conhecidos; confira a página oficial do projeto para a forma de instalação mais atual da sua distribuição.You do not need to memorise everything: there are terminal (TUI) and web interfaces that show system health, logs, SSH, Git and containers visually. The “lazy” ones (lazygit, lazydocker…) follow the idea of folding dozens of commands into keyboard shortcuts. All of the below are well-known open projects; check the project’s official page for the most current install method for your distribution.

No terminal (TUI)In the terminal (TUI)

FerramentaToolPara quêWhat forInstalarInstall
btop · htop · glancessaúde do sistema: CPU, memória, disco, rede e processos num painel ao vivosystem health: CPU, memory, disk, network and processes in a live panelsudo apt install btop htop glances
ncdu“quem está comendo meu disco?”, navegando por pastas por tamanho“what is eating my disk?”, browsing folders by sizesudo apt install ncdu
lazygitGit inteiro com atalhos: stage, commit, branch, rebaseall of Git with shortcuts: stage, commit, branch, rebasegerenciador de pacotes, Homebrew ou binário do GitHubpackage manager, Homebrew or GitHub binary
lazydockercontêineres, imagens, logs e uso de recursos do DockerDocker containers, images, logs and resource useHomebrew, go install ou binário do GitHubHomebrew, go install or GitHub binary
lazyjournalnavegar pelos logs do journalctl e de contêineres com filtrobrowse journalctl and container logs with filteringbinário do GitHub ou HomebrewGitHub binary or Homebrew
sshsmenu para escolher hosts do seu ~/.ssh/config e conectarmenu to pick hosts from your ~/.ssh/config and connectHomebrew, cargo install ou binárioHomebrew, cargo install or binary
bandwhich · nethogs · iftopquem usa a rede: por processo, conexão e host remotowho is using the network: by process, connection and remote hostsudo apt install nethogs iftop
trippy · mtr · gpingtraceroute e ping contínuos, com gráficocontinuous traceroute and ping, with a graphsudo apt install mtr-tiny (mtr); os outros pelo site do projetosudo apt install mtr-tiny (mtr); the others from the project site
termsharko Wireshark no terminalWireshark in the terminalsudo apt install termshark (se disponível) ou bináriosudo apt install termshark (if available) or binary
nmtui · yazi · ranger · fzf · tldrrede por menu · navegador de arquivos · busca difusa · exemplos curtos de comandosnetwork via menu · file browser · fuzzy search · short command examplesrepositório da distribuiçãodistribution repository

Pelo navegador (web)In the browser (web)

FerramentaToolO que mostraWhat it showsComo subirHow to start
Cockpitpainel oficial da Red Hat: saúde, logs, serviços, discos, rede, usuários, firewall e terminal. Boa porta de entrada para ver SSH e o sistema sem decorar comandosthe Red Hat project’s panel: health, logs, services, disks, network, users, firewall and a terminal. A good entry point for watching SSH and the system without memorising commandssudo apt install cockpit && sudo systemctl enable --now cockpit.socket → https://IP:9090
Netdatamilhares de métricas em tempo real, com alertasthousands of real-time metrics with alertsscript oficial de instalação ou pacote; porta 19999. Leia o script antes de executar.official install script or package; port 19999. Read the script before running it.
Glances (modo web)o mesmo painel do glances, no navegadorthe same glances panel, in the browserglances -w → porta 61208
Grafana + Prometheushistórico e painéis para vários servidores (com node_exporter em cada um)history and dashboards for several servers (with node_exporter on each)padrão de mercado; mais trabalho para montarindustry standard; more work to set up
Uptime Kuma“o site/serviço está no ar?”, com avisos“is the site/service up?”, with notificationscontêiner DockerDocker container
Portainergerenciar Docker pela webmanage Docker from the webcontêiner DockerDocker container
Todo painel web é uma porta nova aberta, com poder de administração. Exponha só na sua LAN ou via túnel SSH/VPN (ssh -L 9090:localhost:9090 ana@servidor), com senha forte e, se possível, um segundo fator. Nunca na internet aberta.Every web panel is a new open port with admin power. Expose it only on your LAN or through an SSH tunnel/VPN (ssh -L 9090:localhost:9090 ana@server), with a strong password and, if possible, a second factor. Never on the open internet.

Painel de saúde com comandos purosA health panel using plain commands

uptime                          # há quanto tempo está ligado e o load average
free -h                         # memória (olhe "available", não "free")
df -h                           # discos cheios?
lsblk                           # discos e partições
vmstat 1 5                      # CPU, memória, swap e I/O a cada 1 s
iostat -x 1 3                   # utilização de disco (pacote sysstat)
systemctl --failed              # serviços que falharam
journalctl -p err -b            # erros desde o boot
sudo dmesg -T | tail            # mensagens recentes do kernel (disco, USB, memória)
sensors                         # temperaturas (lm-sensors)
sudo smartctl -H /dev/sda       # saúde do disco (smartmontools)
lscpu ; lspci ; lsusb           # inventário de hardware
uname -r ; cat /etc/os-release  # versão do kernel e da distribuição

Limpar o histórico do terminalClearing the terminal history

O shell guarda os comandos que você digita para poder repeti-los (seta para cima, Ctrl+R). No bash a lista fica na memória durante a sessão e é gravada em ~/.bash_history quando você sai. Por isso uma senha digitada na linha de comando fica gravada em texto puro.The shell keeps the commands you type so you can repeat them (up arrow, Ctrl+R). In bash the list stays in memory during the session and is written to ~/.bash_history when you exit. That is why a password typed on the command line stays stored in plain text.

history | tail -20              # veja os últimos
history -d 482                  # apaga UMA entrada (pelo número)
history -c                      # limpa a lista em MEMÓRIA
history -w                      # grava a memória no arquivo -> junto com -c, zera o arquivo
history -c && history -w        # zerar tudo de uma vez
> ~/.bash_history               # alternativa: esvazia o arquivo direto

Um detalhe que pega muita gente: history -c sozinho limpa só a memória; ao sair, o bash grava de volta o que ainda estiver no arquivo ou o que você digitar depois. Para uma sessão sem rastro, use um dos modos abaixo.A detail that catches many people: history -c alone clears only memory; on exit bash writes back what is still in the file or what you type afterwards. For a session without a trace, use one of the modes below.

Quero…I want…FaçaDoEfeitoEffect
Que esta sessão não seja salvaThis session not to be savedunset HISTFILE ou HISTFILE=/dev/nullao sair, nada é gravadonothing is written on exit
Parar de registrar daqui para frenteStop recording from now onset +o history (volta com set -o history)os próximos comandos nem entram na listathe next commands do not even enter the list
Não gravar um comando sóNot save one commandcomeçar a linha com um espaço (precisa de HISTCONTROL=ignorespace, padrão no Ubuntu)start the line with a space (needs HISTCONTROL=ignorespace, the Ubuntu default)aquela linha é ignoradathat line is ignored
Ignorar padrões para sempreIgnore patterns foreverHISTIGNORE="ls:cd:*senha*" no ~/.bashrccomandos que casam com o padrão não entramcommands that match are not stored
Apagar tudo agoraErase everything nowhistory -c && history -wmemória e arquivo zeradosmemory and file emptied
Limitar o tamanhoLimit the sizeHISTSIZE=1000 · HISTFILESIZE=2000memória e arquivo, respectivamentememory and file, respectively

Outros shells e a telaOther shells and the screen

# zsh: arquivo ~/.zsh_history
: > ~/.zsh_history ; unset HISTFILE ; exit      # esvazia e não regrava ao sair
setopt HIST_IGNORE_SPACE                         # espaço no começo = não grava

# fish
history clear

# limpar a TELA (não é o histórico!)
clear                           # limpa a tela (e, nos terminais modernos, o rolamento)
clear -x                        # limpa a tela mas mantém o rolamento
Ctrl+L                          # limpa a tela, mantém o rolamento
reset                           # reinicializa o terminal se ele "quebrou"

O histórico também vaza por outros lugaresHistory also leaks elsewhere

  • Arquivos de histórico de outros programas: ~/.python_history, ~/.lesshst, ~/.viminfo, ~/.mysql_history, ~/.psql_history.Other programs’ history files: ~/.python_history, ~/.lesshst, ~/.viminfo, ~/.mysql_history, ~/.psql_history.
  • Os logs do sistema: o sudo registra cada comando em /var/log/auth.log ou no journal, e isso não é apagado por limpar o histórico do shell.System logs: sudo records each command in /var/log/auth.log or the journal, and that is not erased by clearing the shell history.
  • A lista de processos: argumentos de linha de comando aparecem para outros usuários em ps e em /proc/PID/cmdline enquanto o comando roda.The process list: command-line arguments are visible to other users in ps and /proc/PID/cmdline while the command runs.
  • Ferramentas de histórico sincronizado (como o atuin) guardam cópias fora do arquivo local.Synced-history tools (such as atuin) keep copies outside the local file.
Se uma senha, token ou chave de API foi digitada e gravada, limpar o histórico não basta: considere o segredo vazado e troque-o. Para o futuro, não coloque segredos em argumentos: leia sem eco (read -rs SENHA), use variáveis de ambiente, arquivos com permissão 600 ou o gerenciador de segredos.If a password, token or API key was typed and stored, clearing the history is not enough: treat the secret as leaked and rotate it. For the future, keep secrets out of arguments: read without echo (read -rs SECRET), use environment variables, files with permission 600 or a secrets manager.
Limpar o seu próprio histórico é privacidade e higiene. Apagar rastros em sistemas que não são seus, ou para esconder atividade de quem administra o ambiente, é outra coisa: em empresas o histórico e os logs costumam ser exigência de auditoria.Clearing your own history is privacy and hygiene. Erasing traces on systems that are not yours, or to hide activity from whoever administers the environment, is something else: in companies, history and logs are often an audit requirement.

Questões de prova e revisãoExam questions and review

Estas perguntas cobrem o que costuma cair em Linux Essentials, LPIC-1 e RHCSA. Tente responder sem olhar a coluna da direita.These questions cover what usually shows up in Linux Essentials, LPIC-1 and RHCSA. Try to answer without looking at the right-hand column.

PerguntaQuestionRespostaAnswer
O que é UID 0 e por que ele importa?What is UID 0 and why does it matter?O superusuário. O kernel ignora as checagens de permissão de arquivos para ele. O que manda é o número, não o nome “root”.The superuser. The kernel skips file permission checks for it. The number matters, not the name “root”.
Qual arquivo guarda os hashes das senhas e quem lê?Which file stores the password hashes, and who can read it?/etc/shadow; só root (o /etc/passwd é legível por todos e só tem um “x”)./etc/shadow; only root (/etc/passwd is world-readable and only has an “x”).
Traduza chmod 640 f e -rwxr-x---.Translate chmod 640 f and -rwxr-x---.640 = dono rw-, grupo r--, outros ---. E rwxr-x--- = 750.640 = owner rw-, group r--, others ---. And rwxr-x--- = 750.
Que permissões tem um arquivo novo com umask 027?What permissions does a new file get with umask 027?666 − 027 = 640 (diretórios: 777 − 027 = 750).666 − 027 = 640 (directories: 777 − 027 = 750).
Para que serve o bit sticky em /tmp?What is the sticky bit on /tmp for?Todos escrevem, mas só o dono do arquivo (ou root) pode apagá-lo ou renomeá-lo.Everyone writes, but only the file’s owner (or root) may delete or rename it.
Por que o passwd consegue mudar o /etc/shadow se o usuário comum não pode?How can passwd change /etc/shadow if a regular user cannot?Ele é setuid root: roda com o UID efetivo do dono do arquivo (root).It is setuid root: it runs with the effective UID of the file’s owner (root).
Qual a diferença entre hard link e link simbólico?What is the difference between a hard link and a symbolic link?Hard link: outro nome para o mesmo inode (não cruza partições). Simbólico: arquivo que guarda um caminho (pode quebrar).Hard link: another name for the same inode (cannot cross partitions). Symbolic: a file that stores a path (can break).
Diferença entre fork() e exec()?Difference between fork() and exec()?fork cria um processo novo (cópia); exec troca o programa do processo atual, mantendo o PID.fork creates a new process (a copy); exec replaces the current process’s program, keeping the PID.
O que é um processo zumbi e um órfão? Como resolver?What are a zombie and an orphan process? How to fix?Zumbi: terminou, mas o pai não deu wait(); resolve-se pelo pai. Órfão: o pai morreu antes; o PID 1 o adota.Zombie: finished, but the parent did not wait(); fix it via the parent. Orphan: the parent died first; PID 1 adopts it.
Qual a diferença entre SIGTERM e SIGKILL?Difference between SIGTERM and SIGKILL?SIGTERM (15) pode ser tratado, permitindo limpeza; SIGKILL (9) não pode ser capturado nem ignorado.SIGTERM (15) can be handled, allowing cleanup; SIGKILL (9) cannot be caught or ignored.
Onde ficam logs, configurações e dados de usuários?Where do logs, configuration and user data live?/var/log, /etc, /home./var/log, /etc, /home.
Que comando lista as portas em escuta e o processo dono?Which command lists listening ports and the owning process?sudo ss -tulpn (ou lsof -i); o antigo netstat -tulpn faz o mesmo.sudo ss -tulpn (or lsof -i); the old netstat -tulpn does the same.
Se ping 1.1.1.1 funciona e ping example.com não, onde está o problema?If ping 1.1.1.1 works and ping example.com does not, where is the problem?DNS (resolução de nomes), não a conectividade.DNS (name resolution), not connectivity.
Qual a política de firewall recomendada para um desktop?What firewall policy is recommended for a desktop?Negar entrada por padrão, permitir saída e respostas a conexões já estabelecidas; liberar só as portas necessárias.Deny incoming by default, allow outgoing and replies to established connections; open only needed ports.
usermod -G dev ana ou usermod -aG dev ana?usermod -G dev ana or usermod -aG dev ana?Com -a (acrescenta). Sem ele, os outros grupos suplementares são removidos.With -a (append). Without it, the other supplementary groups are removed.
Por que sudo echo x > /etc/arquivo falha?Why does sudo echo x > /etc/file fail?O redirecionamento é feito pelo shell do usuário, não pelo sudo. Use | sudo tee.The redirection is done by the user’s shell, not sudo. Use | sudo tee.
history -c apaga o arquivo ~/.bash_history?Does history -c erase ~/.bash_history?Não; só a memória. Combine com history -w ou esvazie o arquivo.No; only memory. Combine with history -w or truncate the file.

Mapa de revisão em uma tabelaReview map in one table

TemaTopicComandos-chaveKey commandsArquivos-chaveKey files
UsuáriosUsersid useradd usermod passwd sudo su visudo/etc/passwd /etc/shadow /etc/group /etc/sudoers
PermissõesPermissionsls -l chmod chown chgrp umask setfacl find -permbits rwx, octal, setuid/setgid/stickyrwx bits, octal, setuid/setgid/sticky
EstruturaStructurels cd pwd df du lsblk mount ln find/etc /var /home /proc /dev /tmp /usr
ProcessosProcessesps top pstree kill nice jobs fg bg systemctl/proc/PID/ journalctl
RedeNetworkip ss ping dig curl nc tcpdump traceroute/etc/hosts /etc/resolv.conf
FirewallFirewallufw nft iptables firewall-cmd/etc/nftables.conf /etc/ufw/
SSHSSHssh ssh-keygen ssh-copy-id scp rsync~/.ssh/ /etc/ssh/sshd_config