Anda di halaman 1dari 57

CAIXA DE FERRAMENTAS UNIX

Esse documento a coleo de comandos e tarefas realizadas nos sistemas Unix/Linux/BSD na qual so utilizados no dia -a-dia dos administradores de redes ou para os usurios avanados. Esse guia prtico e com explicaes diretas, entretanto a leitura supostamente para quem j conhece o assunto. Caixa de Ferramentas UNIX revision 14.1 A ltima verso do documento pode ser achado no link http://cb.vu/unixtoolbox.xhtml. Substitua o .xhtml para .pdf caso queira um documento na verso em PDF e com .book.pdfpara a verso folheto. Em uma impressora frente e verso, criar um pequeno livro pronto para (bind). Essa pgina XHTML pode ser convertida tambm para PDF conforme com a aplicao CSS3 (veja o script de exemplo). Veja tambm o about page. Erros e comentrios so bem-vindos - c@cb.vu Colin Barschel. Colin Barschel 2007-2009. Todos os direitos reservados sob Creative Commons. 1. Sistema 2. Processo 3. Sistema de Arquivo 4. Rede 5. SSH SCP 6. VPN com SSH 7. RSYNC 8. SUDO 9. Arquivos Criptografados 10.Parties Criptografadas 11.Certificados SSL 12.CVS 13.SVN 14.Comandos teis 15.Instalao de Programa 16.Converso de Mdia 17.Imprimindo 18.Banco de Dados 19.Cota de Disco 20.Shells 21.Scripting 22.Programando 23.Ajuda Online white black

SISTEMA
Hardware | Estatsticas | Usurios | Limites | Runlevels | Senha de Root | Compilao de Kernel | Reparos de Grub Executando kernel e a informao do sistema
uname -a # Mostra a verso do kernel (e a verso BSD) lsb_release -a # Informao completa de quaisquer distribuio cat /etc/SuSE -release # Mostra a verso SuSe cat /etc/debian_version # Mostra a verso Debian Usa /etc/ DISTR-release com DISTR= lsb (Ubuntu), redhat, gentoo, mandrake, sun (Solaris), e assim por diante. Veja tambm /etc/issue . # # # #

# uptime # Mostra quanto tempo o sistema est executando, ou seja, qu anto tempo faz que o sistema no desligado # hostname # Mostra na tela o nome da mquina # hostname -i # Exibe o endereo IP da mquina (apenas no Linux) # man hier # Descrio da hierarquia dos arquivos no sistema # last reboot # Exibe o histrico da reinicializao do sistema

In for m a o d o H ar d w ar e
Hardware detectado no kernel
# dmesg # Hardware detectado e mensagens de inicial izao # lsdev # Informao sobre a instalao do hardware # dd if=/dev/mem bs=1k skip=768 count=256 2>/dev/null | strings -n 8 # Leitura da BIOS

Linu x
# cat /proc/cpuinfo # cat /proc/meminfo # grep MemTotal /proc/meminfo # watch -n1 'cat /proc/interrupts' # free -m para MB) # cat /proc/devices # lspci -tv # lsusb -tv # lshal propriedades # dmidecode # Modelo da CPU # Informao da memria # Exibe a memria fsica # Relgio interrompe continuamente mutvel # Mostra o tamanho usado e livre da memria (-m # # # # Dispositivos configurados Mostra os dispositivos PCI Mostra os dispositivos USB Mostra a lista de todos os dispositivos com suas

# Mostra DMI/SMBIOS: como a informao da BIOS

FreeBS D
# sysctl hw.model # sysctl hw # sysctl vm # dmesg | grep "real mem" # sysctl -a | grep mem kernel # sysctl dev # pciconf -l -cv # usbdevs -v # atacontrol list # camcontrol devlist -v # # # # # Mostra o modelo da CPU Mostra vrias informaes do hardware Memria usada Memria do hardware Configuraes e informaes sobre a memria do

# Mostra os dispositivos configurados # Exibe dispositivos PCI # Exibe dispositivos USB # Exibe dispositivos ATA # Exibe dispositivos SCSI

L oa d, es t at s ti c as e m e ns a g e ns
Os comandos a seguir so usados para localizar o que est acontecendo no sistema.
# top # mpstat 1 # vmstat 2 # iostat 2 # systat -vmstat 1 intervalo) # systat -tcp 1 # systat -netstat 1 # systat -ifstat 1 # systat -iostat 1 # tail -n 500 /var/log/messages # tail /var/log/warn syslog.conf # Exibe e atualiza os processos da CPU # Exibe os processos das capacidades relacionadas # a capacidade da memria virtual # Exibe a capacidade I/O (2s intervalo) # Resumo da capacidade do sistema BSD (1s # # # # # # Conexes tcp no BSD (tenta tambm ip) Ativa as conexes de rede BSD BSD trfego de redes ativas BSD taxa de transferncia do disco e da CPU As ltimas 500 linhas mensagens do registro Mensagens de alerta do sistema, vej a em

U s u r i os
# id # Exibe o id, usurio e grupo ativo

# last # Exibe o ultimo usurio logado # who # Exibe o usurio logado # groupadd admin # Adiciona um grupo admin e um usurio colin (Linux/Solaris) # useradd -c "Colin Barschel" -g admin -m colin # usermod -a -G <group> <user> # Adiciona um usurio ao grupo (Debian) # groupmod -A <user> <group> # Adiciona um usurio ao grupo (SuSE) # userdel colin # Exclui o usurio Colin # adduser joe # FreeBSD, adiciona o usurio ao sistema (interativamente) # rmuser joe # FreeBSD, deleta o usurio joe (interativame # pw groupadd admin # Usa pw no FreeBSD # pw groupmod admin -m newmember # Adiciona um novo membro ao grupo # pw useradd colin -c "Colin Barschel" -g admin -m -s /bin/tcsh # pw userdel colin; pw groupdel admin

nte)

Senhas criptografadas esto armazenadas no /etc/shadow nos Linux e Solaris, no FreeBSD esto localizadas no /etc/master.passwd. Se o master.passwd for modificado manualmente (deleta a senha), executa # pwd_mkdb -p master.passwd para repor o banco de dados. Para prevenir amplos acessos temporrios (para todos os usurios mas root) use nologin. A mensagem do nologin ser Exibido (talvez no trabalha com as chaves ssh).
# echo "Desculpe no acessa agora" > /etc/nologin # echo "Desculpe no ac essa agora" > /var/run/nologin # (Linux) # (FreeBSD)

L i m i te s
Algumas aplicaes requerem limites superiores em arquivos abertos (como o Proxy do servidor de web, banco de dados). O limite padro so normalmente mais baixos. Linu x Cada Shell/script O limite do Shell regido por um ulimit. O estado checado com ulimit -a. Por exemplo, para trocar os arquivos limites dos 1024 para 10240 faa:
# ulimit -n 10240 # Isso apenas validar dentro do Shell O comando ulimit pode ser usado no em um script para trocar os limites do script apenas.

Por usurio/proce sso Acesso de aplicaes e usurios podem ser configurados no /etc/security/limits.conf . Por exemplo:
# cat /etc/security/limits.conf * hard nproc 250 asterisk hard nofile 409600 # Limit es de processos por usurios # Aplicaes limites de arquivos abertos

Sistema amplo Limites do kernel so ajustados sysctl. Limites permanentes so ajustados no /etc/sysctl.conf .
# sysctl -a # Visualiza todo o limite do sistema # sysctl fs.file -max # Visualiza o limite mximo de arquivos abertos # sysctl fs.file -max=102400 # Troca o limite mximo # echo "1024 50000" > /proc/sys/net/ipv4/ip_local_port_range #Faixa de po rtas # cat /etc/sysctl.conf fs.file-max=102400 # Permanece a entrada no sysctl.conf # cat /proc/sys/fs/file -nr # Como muitos arquivos descritos em uso

FreeBS D Cada Shell/script Use o comando limits em csh ou tcsh ou igual ao Linux, use ulimit no bash shell.

Por usurio/proce sso O padro dos limites de acesso so configurados no /etc/login.conf . Um valor ilimitado ainda limitado pelo sistema de valor mximo. Sistema amplo Limites do kernel tambm so definidas no sysctl. Permanece os limites que so definidos no
/etc/sysctl.conf ou /boot/loader.conf . A sintaxe igual ao Linux mas as chaves so

diferentes.
# sysctl -a # Visualiza todo o limite do sistema # sysctl kern.maxfiles=XXXX # Nmero mximo de descritores no arquivo kern.ipc.nmbclusters=32768 # Permanece a entrada no /etc/sysctl.conf kern.maxfiles=65536 # Tpico valor do squid kern.maxfilesperproc=32768 kern.ipc.somaxconn= 8192 # Fila TCP. Melhor para apache/sendmail # sysctl kern.openfiles # Quantos arquivos descritos so usados. # sysctl kern.ipc.numopensockets # Quantos sockets esto em uso # sysctl -w net.inet.ip.portrange.last=50000 # Padr o 1024-5000 # netstat -m # Capacidade de memria da rede

Veja o FreeBSD handbook Chapter 11http://www.freebsd.org/handbook/configtuning-kernellimits.html para detalhes. Solaris Seguindo os valores no /etc/system incrementar o mximo de descries por proc::
set rlim_fd_max = 4096 nico proc set rlim_fd_cur = 1024 proc # Limite fsico nos arquivos de descries para o # Limite lgico nas filas descritas para o nico

Ru nl ev e ls
Linu x Uma vez iniciado o kernel inicia o init que ento comea o rc que inicia todos os scripts pertencente a um runlevel. O scripts so armazenados em um /etc/init.d e so liga dos a um /etc/rc.d/rcN.d com N o nmero do runlevel. O nvel padro do runlevel configurado em /etc/inittab. So normalmente 3 ou 5:
# grep default: /etc/inittab id:3:initdefault:

O atual runlevel pode ser altera do com init . Por exemplo para ir do 3 para o 5:
# init 5 y y y y y y # Entra o runlevel 5

0 1 2 3 5 6

Desliga e suspende Modo Single-User (also S) Multi-user sem rede Multi-user com rede Multi-user com X Reinicia

Use chkconfig para configurar os programas que inicializar o boot pelo runlevel.
# # # # chkconfig chkconfig chkconfig chkconfig --list --list sshd sshd --level 35 on sshd off # Lista todos os scripts do init # Relata o estado do sshd # Configura sshd para level 3 e 5 # Desabilita sshd todos os runlevels

Debian e distribuies baseadas no Debian como Ubuntu ou Knoppix usa o comando updaterc.d para gerenciar o script do runlevel. Por padro comea em 2,3,4 e 5 e shutdown no 0,1 e 6.
# update-rc.d sshd defaults # Ativa sshd como runlevel padro # update-rc.d sshd start 20 2 3 4 5 . stop 20 0 1 6 . # Com argumentos explcitos

# update-rc.d -f sshd remove # shutdown -h now (or # poweroff)

# Desabilita sshd para todos runlevels # Desliga o sistema ou suspende

FreeBS D O boot do BSD se aproxima do sistema SysV, no existem runlevels. O final do estado (nico usurio, com ou sem X) configurado no /etc/ttys . Todos os scripts esto localizado no /etc/rc.d/ e no /usr/local/etc/rc.d/ a terceira parte das aplicaes. A ativao do servio est configurado no /etc/rc.conf e /etc/rc.conf.local . Por padro est configurado no /etc/defaults/rc.conf . O script responde pelo menos para start|stop|status.
# /etc/rc.d/sshd status sshd is running as pid 552. # shutdown now # Entra no modo single -user # exit # volta para o modo multi -usurio # shutdown -p now # Desliga e suspende o sistema # shutdown -r now # Reiniciat O processo do init pode ser usado para checar um dos seguintes runlevels. Por exemplo # init 6 para reiniciar. y y y y y

0 1 6 c q

Desliga o sistema (sinal USR2) Vai o modo single-user (sinal TERM) Reinicia a mquina (sinal INT) Bloqueia o acesso adicional TSTP) Rescan o arquivo ttys(5) (sinal HUP)

Zer ar s e nh a d e Root
Linu x mto do 1 Ao boot carrega (lilo ou grub), entra a opo seleo de inicializao:
init=/bin/sh

O kernel montar a partio e o init inicializar o bourne Shell em vez do rc e o runlevel. Usa o comando passwd para trocar a senha e reinicia.Esquea o modo single -user, voc precisa da senha para isso. Se, depois do booting, a partio root montado para somente para leitura, e remonta como rw:
# # # # mount -o remount,rw / passwd sync; mount -o remount,ro / reboot # ou deleta a senha de root no (/etc/shadow) # sync depois de remontar para somente leitura

FreeBS D mto do 1 No FreeBSD, inicia o single-user, remonta / rw e a senha. Voc pode selecionar o modo single-user menu (opo 4) como Exibe na tela 10 segundos para iniciar. O modo single -user dar o Shell root da partio /.
# mount -u /; mount -a # passwd # reboot # montar / rw

Unixes e FreeBSD e Li nux m todo 2 Outros Unixes no poderia deix -lo ir embora com o truque simples init. A soluo montada na partio de outro SO (como um CD) e troca a senha no disco.
y y y

Inicia o CD live ou a instalao em um mo do de recuperao que vai lhe dar um Shell Procura a partio root com fdisk /dev/sda Monta e usa o chroot

# # # #

mount -o rw /dev/ad4s3a /mnt chroot /mnt passwd reboot

# chroot into /mnt

M d ul os d o K er n e l
Linu x
# lsmod # modprobe isdn # lista todos os mdulos carregados # Carrega um mdulo

FreeBS D
# kldstat # kldload crypto #Lista todos os mdulos carregados # Para carregar um mdul o

Com p i l an d o o K er n el
Linu x
# # # # # # # # # cd /usr/src/linux make mrproper make oldconfig make menuconfig make make modules make modules_install make install reboot # # # # # # # Limpa o antigo .config se existir Re -usa o antigo .config se existente ou xconfig (Qt) ou g config (GTK) Cria uma imagem comprimida Compila os mdulos Instala os mdulos Instala o kernel

FreeBS D Atualizao opcional de origem (em /usr/src ) com csup (como FreeBSD 6.2 ou posterior):
# csup <supfile>

Eu sigo o supfile:
*default *default *default *default src-all host=cvsup5.FreeBSD.org # www.freebsd.org/handbook/cvsup.html#CVSUP -MIRRORS prefix=/usr base=/var/db release=cvs delete tag=RELENG_7

Modifica e refaz o kernel, copia a configurao de arquivo genrica para o novo nome e edita como se precisa (voc pode tambm editar o arquivo GENERIC diretamente). Para reiniciar a construo e aps a interrupo, adiciona a opo NO_CLEAN=YES , o comando make evita a limpeza dos objetos j formados.
# # # # # cd /usr/src/sys/i386/conf/ cp GENERIC MYKERNEL cd /usr/src make buildkernel KERNCONF=MYKERNEL make installkernel KERNCONF=MYKERNEL # Constri total o SO mas no o kernel # Usa KERNCONF para ambos # Compare somente os arquivos essenciais e

Para a reconstruo total SO:


# make buildworld # make buildkernel # make installkernel # reboot # mergemaster -p conhecidos # make installworld # mergemaster -i -U arquivos # reboot

# Atualiza todas as configuraes e outros

Para pequenas alteraes no fonte, voc pode usar NO_CLEAN=yes para evitar a reconstruo de toda a rvore.
# make buildworld NO_CLEAN=yes # No deleta os objetos antigos # make buildkernel KERNCONF=MYKERNEL NO_CLEAN=yes

Re p ar a o G r u b
Ento voc quebrou o grub? Boot com CD live, [procura sua partio Linux abaixo /dev e use o fdisk para localizar a partio do linux] monte a partio linux, adicione o /proc e o /dev e use o grub-install /dev/xyz . Suponha que o linux esta em /dev/sda6 :
# # # # # mount /dev/sda6 /mnt mount --bind /proc /mnt/pr oc mount --bind /dev /mnt/dev chroot /mnt grub-install /dev/sda # Monta a partio linux em /mnt # monta o subsistema proc no /mnt # monta os dispositivos no /mnt # troca a partio root Linux # reinstala grub com suas antigas config uraes

PROCESSOS
Listando | Prioridade | Background/Foreground | Top | Kill

L is t a g e m e PID s
Cada processo tem um nmero exclusivo, o PID. A lista de todos os processo em execuo obtido com o ps.
# ps -auxefw # Lista extensa de todos os processos em execuo

No entanto o uso mais tpico com o pipe ou o pgrep :


# ps axww | grep cron 586 ?? Is 0:01.48 /usr/sbin/cron -s # ps axjf # Todos processo s no formato de rvore(Linux) # ps aux | grep 'ss[h]' # Localiza todos pids ssh sem o grep pid # pgrep -l sshd # Localiza os PIDs dos processos por (parte de) nome # echo $$ # O PID de sua shell # fuser -va 22/tcp # Lista os processos usando a porta 22 (Linux) # pmap PID # Mapa dos processos em memria (Caa vazamentos de memria) (Linux) # fuser -va /home # Lista os processos acessing a partio /home # strace df # Traa os sinais e chamadas de sistema # truss df # Mesmo que acima em FreeBSD/Solaris/Unixware

Pr i or i d a d e
Altera a prioridade dos processos em execuo com renice . Nmero negativos tem uma prioridade maior , o menor -20 e o "nice" tem um valor positivo.
# renice -5 586 # Maior Prioridade 586: Prioridade antiga 0, nova prioridade -5 Inicia o processo com uma prioridade definida com o nice. Positivo "nice" ou fraco, negativo fixa uma prioridade forte. Certifique se /usr/bin/nice ou o shell embutido usou (Verifique com # which nice ). # nice -n -5 top # Prioridade forte(/usr/bin/nice) # nice -n 5 top # Prioridade fraca (/usr/bin/nice) # nice +5 top # tcsh tem nice embutido (mesmo que acima!)

Enquanto o nice altera o agendamento da CPU, um outro comando til o ionice, ir fixar o IO do disco. Isto muito til para aplicaes intensivas (ex. compilao). Voce pode selecionar uma classe (ociosa - melhor esforo - tempo real ), a pgina do manu al curta e bem explicativa.
# ionice c3 -p123 Somente) # ionice -c2 -n0 firefox prioridade # ajusta a classe ociosa para o PID 123 (Linux # Executa o firefox com melhor esforo e maior

# ionice -c3 -p$$

# Ajusta o shell atual para prioridade ociosa

O ultimo comando muito til para compilar (ou debugar) um longo projeto. Cada comando iniciado neste shell ter a prioridade herdada. $$ o seu shell pid (tente echo $$). FreeBSD usa idprio/rtprio (0= mxima prioridade, 31 = mais inativo)
# idprio 31 make # idprio 31 -1234 # idprio -t -1234 real/ociosa # Compila com menor prioridade # Ajusta o PID 1234 com menor prioridade # -t remove qualquer prioridade de temp o

Ba c k gr ou n d /F or e gr oun d
Quando iniciado a partir de um shell, os processos podem ser levados ao background e ao foreground com [Ctrl]-[Z] (^Z), bg e fg. Lista os processos com jobs.
# ping cb.vu > ping.log ^Z # ping interrompido (parado) com [Ctrl] -[Z] # bg # Coloca em segundo plano e continua executando # jobs -l # Lista os processos em segundo plano [1] - 36232 Running ping cb.vu > ping.log [2] + 36233 Suspended (tty output) top # fg %2 # Traz o processo 2 de volta ao primeiro plano Use nohup para iniciar o processo que tem que continuar a executar quan do a shell fechada. # nohup ping -i 60 > ping.log &

Top
O programa top exibe informaes dos processos em execuo. Veja tambm o programa htop de htop.sourceforge.net (a verso mais poderosa do top) que roda em Linux e FreeBSD (ports/sysutils/htop/ ). Enquanto o top executado pressione a tecla "h" para uma viso geral da ajuda. Teclas teis so:
y y y y

u [nome do usurio] Para exibir somente os processos pertencentes ao usurio. Use + ou deixe em branco para todos os usurios. k [pid] Finaliza todos os processos com o pid. 1 Para exibir todas as estatsticas dos processos (Linux somente) R Para ordenar.

Si gn a ls /K il l
Termina ou manda um sinal com kill ou killall .
# ping -i 60 cb.vu > ping.log & [1] 4712 # kill -s TERM 4712 # killall -1 httpd # pkill -9 http # pkill -TERM -u www # fuser -k -TERM -m /home desmontar) # mesmo que finalizar com -15 4712 # Kill HUP processos por nome # Kill TERM processos por (parte de) nome # Kill TERM processos usado po r www # Kill cada processo acessando /home (para

Sinais importantes so:


y y y y y

1 2 3 9 15

HUP (desliga) INT (suspende) QUIT (fecha) KILL (fora) TERM (software envia o sinal de trmino)

SISTEMA DE ARQUIVOS

Info de disco | Boot | Uso de disco | Arquivos abertos | Monta/remonta | Monta SMB | Monta imagem | Queima ISO | Criar image | Memria de Disco | Desempenho de Disco

P er mi s s es
Altere as permisses e propriedades com chmod e chown . A umask padro pode ser alterada para todos os usurios em /etc/profile para Linux ou /etc/login.conf para FreeBSD. A umask padro geralmente 022. A umask subtrado de 777, assim a umask 022 resulta na permisso de 755.
1 --x executa # Modo 764 = executa/l/escreve | l/escreve | l 2 -w- escreve # Para: | -- Dono --| |- Grupo-| |Outros| 4 r-- l ugo=a u=usurio, g=grupo, o=outros, a=todos # chmod [OPO] M ODO[,MODO] ARQUIVO # MODO na forma [ugoa]*([ -+=]([rwxXst])) # chmod 640 /var/log/maillog # Restringir o log -rw-r----# chmod u=rw,g=r,o= /var/log/maillog # O mesmo acima # chmod -R o-r /home/* # Remove recursivamente leitura pa ra outros para todos os usurios # chmod u+s /path/to/prog # Fixa SUID bit no executvel (saiba o que esta fazendo!) # find / -perm -u+s -print # Localiza todos os programas com o SUID bit # chown user:group /path/to/file # Altera a propriedade do usurio e o grupo no arquivo # chgrp group /path/to/file # Altera a propriedade da grupo no arquivo # chmod 640 `find ./ -type f -print` # Altera a propriedade para 640 em todos os arquivos # chmod 751 `find ./ -type d -print` # Altera a permisso para 751 para todos os diretrios

In for m a o d e D is c o
# # # # diskinfo -v /dev/ad2 hdparm -I /dev/sda fdisk /dev/ad 2 smartctl -a /dev/ad2 # # # # Informao sobre Informao sobre Exibe e manipula O SMART exibe as o disco (Setor/tamanho) FreeBSD o disco IDE/ATA (Linux) a tabela de parties informao do disco

Boot
FreeBS D Para inicializar o antigo kernel se o novo kernel no inicializar, pare o boot durante a contagem regressiva
# unload # load kernel.old # boot

Sis t e m a d e p ont o d e m on t a g e m /U s o d e dis c o


# mount | column -t sistema # df montados # cat /proc/partitions # Exibe o sistema de arquivos montados no seu # Exibe o espao livre no disco e disposi tivos # Exibe todas parties registradas (Linux)

Uso de Disco
# # # # du du du ls -sh * -csh -ks * | sort -n -r -lSr # # # # Lista o tamanho dos diretrios Tamanho total do diretrio corrente Ordena tudo por tamanho em kilobytes Exibe arquivos, maiores por ltimo

Q u e m t e m ar qu iv os a b er t os
Este muito til para localizar quem esta bloqueando a partio e tem que ser desmontado e recebe um erro tpico:
# umount /home/ umount: unmount of /home bloqueando o home Falhou: Dispositivo Ocupado # Impossvel desmontar porque um arquivo esta

FreeBS D e ma io ria dos Unixes


# fstat -f /home # fstat -p PID # fstat -u user # Para montar o ponto # Para uma aplicao com PID # Para um nome de usurio

Localiza arquivos de log aberto (ou outros arquivos abertos), pela palavra Xorg:
# ps ax | grep Xorg | awk '{p rint $1}' 1252 # fstat -p 1252 USER CMD PID FD MOUNT INUM MODE root Xorg 1252 root / 2 drwxr -xr-x root Xorg 1252 text /usr 216016 -rws--x--x root Xorg 1252 0 /var 212042 -rw-r--r--

O arquivo com inum 212042 o nico arquivo em /var:


# find -x /var -inum 212042 /var/log/Xorg.0.log

SZ|DV R/W 512 r 1679848 r 56987 w

Linu x Localiza arquivos abertos em um ponto de montagem: fuser ou lsof:


# fuser -m /home # lsof /home COMMAND PID USER tcsh 29029 eedcoba lsof 29140 eedcoba # Lista os processos acessando o /home FD cwd cwd TYPE DEVICE DIR 0,18 DIR 0,18 SIZE 12288 12288 NODE NAME 1048587 /home/eedcoba (guam:/home) 1048587 /home/eedcoba (guam:/home)

Sobre uma aplicao:


ps ax | grep Xorg | awk '{print $1}' 3324 # lsof -p 3324 COMMAND PID USER FD TYPE DEVICE Xorg 3324 root 0w REG 8,6

SIZE 56296

NODE NAME 12492 /var/log/Xorg.0.lo g

Sobre um arquivo nico:


# lsof /var/log/Xorg.0.log COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME Xorg 3324 root 0w REG 8,6 56296 12492 /var/log/Xorg.0.log

M on t a nd o e Re m on t an d o u m Sis t e m a d e Ar qu iv os
Por exemplo, o cdrom. Se listado em /etc/fstab
# mount /cdrom

Ou localize o dispositivo em /dev ou com o dmesg FreeBS D


# mount -v -t cd9660 /dev/cd0c /mnt # mount_cd9660 /dev/wcd0c /cdrom # mount -v -t msdos /dev/fd0c /mnt # cdrom # outro mtodo # disquete FStype cd9660 Options ro,noauto Dump 0 Pass# 0

Entrada no /etc/fstab:
# Device /dev/acd0 Mountpoint /cdrom # Ou inserir

Para permitir o usurio fazer:


# sysctl vfs.usermount=1 a linha "vfs.usermount=1" em /etc/sysctl.conf

Linu x
# # # # mount mount mount mount -t auto /dev/cdrom /mnt/cdrom # Tpico comando para montar cdrom /dev/hdc -t iso9660 -r /cdrom # Tpico IDE /dev/scd0 -t iso9660 -r /cdrom # Tpico SCSI cdrom /dev/sd c0 -t ntfs-3g /windows # Tpico SCSI /media/cdrom subfs noauto,fs=cdfss,ro,procuid,nosuid,nodev,exec 0 0

Entrada no /etc/fstab:
/dev/cdrom

Montar uma Partio Free BSD com Linux Localize o nmero da partio com fdisk, esta geralmente a partio root, mas poderia ser outro slice BSD tambm. Se o FreeBSD tem muitas slices, eles no so o que esto listados na tabela fdisk, porm visvel em /dev/sda* ou /dev/hda*.
# fdisk /dev/sd a # Localiza a partio FreeBSD /dev/sda3 * 5357 7905 20474842+ a5 FreeBSD # mount -t ufs -o ufstype=ufs2,ro /dev/sda3 /mnt /dev/sda10 = /tmp; /dev/sda11 /usr # Outros slices

Remo ntar Remontar um dispositivo sem d esmontar. Necessrio para fsck por exemplo
# mount -o remount,ro / # mount -o ro / # dd if=/dev/cd0c of=file.iso # Linux # FreeBSD

Copie os dados brutos a partir do cdrom em uma imagem iso:

A di c i on ar s w a p e m t e m p o r e a l
Suponha que voc necessite de mais swap (agora mesmo), um arquivo de 2GB em /swap2gb (Linux comente).
# # # # # dd if=/dev/zero of=/swap2gb bs=1024k count=2000 mkswap /swap2gb # Criar a rea de Swap swapon /swap2gb # Ativ e a swap. Agora em uso! swapoff /swap2gb # Quando terminar, desative a swap rm /swap2gb

M on t ar u m Com p ar t il h a m e nt o S M B
Suponha que ns queremos acessar o compartilhamento SMB em um computador smbserver, o endereo digitado em um computador Windows \\smbserver\myshare. Ns montamos em /mnt/smbshare. Alerta> cifs precisa de um IP ou nome DNS, no um nome Windows. Linu x
# smbclient -U user -I 192.168.16.229 -L //smbshare/ # Lista os compartilhamentos # mount -t smbfs -o username=winuser //smbserver/myshare /mnt/smbshare # mount -t cifs -o username=winuser,password=winpwd //192.168.16.229/myshare /mnt/share

Adicionando com o pacote mount.cifs possvel armazenar as credenciais em um arquivo, por exemplo /home/user/.smb :
username=winuser password=winpwd

E montar os seguintes:
# mount -t cifs -o credentials=/home/user/.smb //192.168.16.229/myshare /mnt/smbshare

FreeBS D Use -I para pegar o IP (ou nome DNS); smbserver o nome Windows.
# smbutil view -I 192.168.16.229 //winuser@smbserver # List os compartilhamentos # mount_smbfs -I 192.168.16.229 //winuser@smbserver/myshare /mnt/smbshare

M on t ar u m a i m a g e m
Voltando ao Linux
# mount -t iso9660 -o loop file.iso /mnt # mount -t ext3 -o loop file.img /mnt de arquivos ext3 # Monta uma imagem de CD # Monta uma imagem com sistema

FreeBS D Com dispositivo de memria (faa # kldload md.ko se necessrio):


# mdconfig -a -t vnode -f file.iso -u 0 # mount -t cd9660 /dev/md0 /mnt # umount /mnt; mdconfig -d -u 0 # Limpeza do dispositivo md

Ou com n virtual:
# vnconfig /de v/vn0c file.iso; mount -t cd9660 /dev/vn0c /mnt # umount /mnt; vnconfig -u /dev/vn0c # Limpeza do dispositivo vn

Solaris e FreeBS D Voltando ao incio com a interface do arquivo ou lofi:


# lofiadm -a file.iso # mount -F hsfs -o ro /dev/l ofi/1 /mnt # umount /mnt; lofiadm -d /dev/lofi/1 # Limpeza do dispositivo lofi

Cr i ar e Q u e i m ar u m a i m a g e m I SO
Isto ir copiar setor por setor de um cd ou DVD. Com conv=notrunc , a imagem ser menor se ouver contedo no cd. Veja abaixo o dd examples.
# dd if=/dev/hdc of=/tmp/mycd.iso bs=2048 conv=notrunc

Use mkisofs para criar uma imagem CD/DVD de arquivos em um diretrio. Para evitar a restries de nomes de arquivos: -r permite a extenso Rock Ridge comuns ao sistema UNIX, -J permite extenso Joliet usada por sistemas Microsoft. -L permite arquivos ISO9660 comeando com um perodo.
# mkisofs -J -L -r -V TITLE -o imagefile.iso /path/to/dir

Em FreeBSD, mkisofs encontrado no ports em sysutils/cdrtools. Queimar uma im agem ISO de CD/DVD Free BSD FreeBSD no ativa DMA em dispositivos ATAPI por padro. DMA est habilitado com o comando sysctl e os argumentos abaixo, ou com /boot/loader.conf com as seguintes entradas::
hw.ata.ata_dma="1" hw.ata.atapi_dma="1" Use burncd com um dispositivo ATAPI( burncd parte da base do sistema) e cdrecord ( em

sysutils/cdrtools) com um disco SCSI.


# burncd -f /dev/acd0 data imagefile.iso fixate # Para discos ATAPI # cdrecord -scanbus # Para localizar o dispositivo (like 1,0,0) # cdrecord dev=1,0,0 imagefile.iso

Linux Tambm usa cdrecord com Linux como descrito acima. Alm disso possvel usar a interface ATAPI nativa que se encontra com:
# cdrecord dev=ATAPI -scanbus

E queime o CD/DVD como acima. Fe rramentas dvd+rw

O dvd+rw-tools pacote (FreeBSD: ports/sysutils/dvd+rw-tools) pode fazer tudo e inclui growisofs para queimar CDs ou DVDs. Os exemplos se referem aos dispositivos de DVD /dev/dvd que poderia ser um link simblico para /dev/scd0 (tpico scsi em Linux) ou /dev/cd0 (tpico FreeBSD) ou /dev/rcd0c (tpico NetBSD/OpenBSD de carter SCSI) ou /dev/rdsk/c0t1d 0s2 (Exemplo de um dispositivo Solaris SCSI/ATAPI CD -ROM ). Existe uma boa documentao com exemplos em FreeBSD handbook chapter 18.7http://www.freebsd.org/handbook/creating-dvds.html.
# -dvd-compat finaliza o disco # growisofs -dvd-compat -Z /dev/dvd=imagefile.iso # Queima uma imagem iso existente # growisofs -dvd-compat -Z /dev/dvd -J -R /p/to/data # Queima diretamente

Conve rte r um arquivo do Ne ro .n rg para .iso O nero simplesmente adiciona um cabealho de 300Kb para uma imagem iso normal. Isto pode ser mudado com o dd.
# dd bs=1k if=imagefile.nrg of=imagefile.iso skip=300

Conve rte r uma imagem / bin/ cue para .iso O pequeno bchunk programhttp://freshmeat.net/projects/bchunk/ pode fazer isso. E no ports do FreeBSD em sysutils/bchunk.
# bchunk imagefile.bin imagefile.cue imagefile.iso

Cr i ar u m ar qu iv o b a s e a d o e m u m a i m a g e m
Por exemplo, uma partio de 1GB usando o arquivo /usr/vdisk.img. Aqui usamos o vnode 0, mas tambm poderia ser o 1. FreeBS D
# # # # # # dd if=/dev/random of=/usr/vdisk.img bs=1K count=1M mdconfig -a -t vnode -f /usr/vdisk.img -u 0 bsdlabel -w /dev/md0 newfs /dev/md0c mount /dev/md0c /mnt umount /mnt; mdconfig -d -u 0; rm /usr/vdisk.img # Cria o dispositivo /d ev/md1

O arquivo de imagem base pode ser automaticamente montado durante o boot com uma entrada em /etc/rc.conf and /etc/fstab. Teste sua instalao com # /etc/rc.d/mdconfig start (primeiro delete o dispositivo md0 com # mdconfig -d -u 0). Note, porm, que essa configurao automtica s funcionar se o arquivo de imagem no na partio root. A razo que o script /etc/rc.d/mdconfig executada muito cedo durante a inicializao e a partio raiz ainda somente leitura. Imagens localizadas fora da partio raiz ser montado mais tarde com o script /etc/rc.d/mdconfig2. /boot/loader.conf:
md_load="YES"

# Cleanup the md device

/etc/rc.conf:

# mdconfig_md0=" -t vnode -f /usr/vdisk.img" partition

# /usr is not on the root

/etc/fstab: (Os 0 0 no final so importantes, diz ao fsck para ignorar este dispositivo, como ainda no existe)
/dev/md0 /usr/vdisk ufs rw 0 0

Tambm possvel aumentar o tamanho da imagem depois, dizer, por exemplo, 300 MB de maior dimenso.
# umount /mnt; mdconfig -d -u 0 # dd if=/dev/zero bs=1m count=300 >> /usr/vdisk.img # mdconfig -a -t vnode -f /usr/vdisk.img -u 0 # growfs /dev/md0 # mount /dev/md0c /mnt agora 300MB

# A maior partio de arquivos

Linu x
# # # # dd if=/dev/zero of=/usr/vdisk.img bs=1024k count=1024 mkfs.ext3 /usr/vdisk.img mount -o loop /usr/vdisk.img /mnt umount /mnt; r m /usr/vdisk.img # Limpeza

Linu x with losetup


/dev/zero muito mais rpido urandom , mas menos segura para criptografia # dd if=/dev/urandom of=/usr/vdisk.img bs=1024k count=1024 # losetup /dev/loop0 /usr/vdisk.img # Cria e associa /dev/loop0 # mkfs.ext3 /dev/loop0 # mount /dev/loop0 /mnt # losetup -a # Verifica os loops utilizados # umount /mnt # losetup -d /dev/loop0 # Separa # rm /usr/vdisk.img

Cr i ar u m S is t e m a d e Ar qu iv os de M e m r i a
A memria do sistema de arquivos baseado muito rpido para a aplicao de IO pesado. Como criar uma partio de 64 MB montado em / memdisk: FreeBS D
# mount_mfs -o rw -s 64M md /memdisk # umount /memdisk; mdconfig -d -u 0 md /memdisk mfs rw, -s64M # Limpeza do dispositivo md # entrada /etc/fstab

Linu x
# mount -t tmpfs -osize=64m tmpfs /memdisk

D es e m p e nh o d e D is c o
Ler e escrever um arquivo de 1GB na partio ad4s3c (/home)
# time dd if=/dev/ad4s3c of=/dev/null bs=1024k count=1000 # time dd if=/dev/zero bs=1024k count=1000 of=/home/1Gb.file # hdparm -tT /dev/hda # Somente Linux

NETWORK
Roteamento | Adicionar IP | Alterar MAC | Portas | Firewall | IP Forward | NAT | DNS | DHCP | Trfego | QoS | NIS | Netcat

D e bu g g in g ( Ve ja m a is Tr a ffi c a n a ly s is )
Linu x
# ethtool # ethtool # ethtool # ethtool # ip link ifconfig) # ip link eth0 up" # ip addr ifconfig) eth0 # Mostra o estado da ethernet (substitui mii -diag) -s eth0 speed 100 duplex full # Fora 100Mbit Full duplex -s eth0 autoneg off # Desabilita auto negociao -p eth1 # Pisca o led da ethernet - muito til quando suportado show # Mostra todas as interfaces no Linux (semelhante ao set eth0 up show # Levanta o dispositivo (ou desce). O mesmo que "ifconfig # Mostra todos os endereos IP no linux (semelhante ao

# ip neigh show

# Semelhante ao arp

-a

Outros OS 's
# # # # # # ifconfig fxp0 # Verifica o campo "media" no FreeBSD arp -a # Verifica o Roteador (ou host) entrada ARP (todos OS) ping cb.vu # A primeira coisa a tentar... traceroute cb.vu # Imprime o caminho de rota para o destino ifconfig fxp0 media 100baseTX mediaopt full -duplex # 100Mbit full duplex (FreeBSD) netstat -s # Estatsticas do Sistema para protocolo de rede

Comandos adicionais que nem sempre so instalados por padro, mas fcil de encontrar:
# arping 192.168.16.254 # Ping na camada ethernet # tcptraceroute -f 5 cb.vu # Utiliza o TCP ao invs de icmp para rastrear firewalls

Rot e a m e n t o
Im primin do Tabe la de Ro teamento
# route -n # netstat -rn # route print # Linux ou use "ip route" # Linux, BSD and UNIX # Windows

Adiciona e Deleta Ro tas Free BSD


# route add 212.117.0.0/16 192.168.1.1 # route delete 212.117.0.0/16 # route add default 192.168.1.1

Adiciona rota permanente em /etc/rc.conf


static_routes="myroute" route_myroute=" -net 212.117.0.0/16 192.168.1.1"

Linux
# # # # # # route add -net 192.168.20.0 netma sk 255.255.255.0 gw 192.168.16.254 ip route add 192.168.20.0/24 via 192.168.16.254 # mesmo que acima com ip route route add -net 192.168.20.0 netmask 255.255.255.0 dev eth0 route add default gw 192.168.51.254 ip route add default via 192.168. 51.254 dev eth0 # mesmo que acima com ip route route delete -net 192.168.20.0 netmask 255.255.255.0

Solaris
# route add -net 192.168.20.0 -netmask 255.255.255.0 192.168.16.254 # route add default 192.168.51.254 1 # 1 = saltos para gateway # route change default 192.168.50.254 1 Entradas permanentes so estabelecidas em /etc/defaultrouter . o prximo

Windows
# Route add 192.168.50.0 mask 255.255.255.0 192.168.51.253 # Route add 0.0.0.0 mask 0.0.0.0 192.168.51.254

Use add -p para criar uma rota persistente.

Con fi g ur e En d er e os IP a di c i on ai s
Linu x
# # # # ifconfig eth0 192.168.50.254 netmask 255.255.255.0 ifconfig eth0:0 192.168.51.254 netmask 255.255.255.0 ip addr add 192.168.50.2 54/24 dev eth0 ip addr add 192.168.51.254/24 dev eth0 label eth0:1 # Primeiro IP # Segundo IP # Equivalente ao comando ip

FreeBS D
# ifconfig fxp0 inet 192.168.50.254/24 # Primeiro IP # ifconfig fxp0 alias 192.168.51.254 netmask 255.255.255.0 # Segundo IP # ifconfig fxp0 -alias 192.168.51.254 # Remove o segundo apelido IP

Permanent entries in /etc/rc.conf


ifconfig_fxp0="inet 192.168.50.254 netmask 255.255.255.0" ifconfig_fxp0_alias0="192.168.51.254 netmask 255.255.255.0"

Solaris Check the settings with ifconfig -a # ifconfig hme0 plumb # Enable the network card # ifconfig hme0 192.168.50.254 netmask 255.255.255.0 up # First IP # ifconfig hme0:1 192.168.51.254 netmask 255.255.255.0 u p # Second IP

A lt er ar En d er e o M A C
Normalmente voc tem que derrubar a relao antes da mudana. No me diga porque voc quer mudar o endereo MAC ...
# # # # # # ifconfig eth0 ifconfig eth0 ifconfig fxp0 ifconfig hme0 sudo ifconfig sudo ifconfig down hw ether 00:01:02:03:04:05 link 00:0 1:02:03:04:05 ether 00:01:02:03:04:05 en0 ether 00:01:02:03:04:05 en0 lladdr 00:01:02:03:04:05 # Linux # FreeBSD # Solaris # Mac OS X Tiger # Mac OS X Leopard

Muitas ferramentas existentes para Windows. Por Exemplo etherchangehttp://ntsecurity.nu/toolbox/etherchange. Ou procure por "Mac Makeup", "smac".

P or t a s e m U s o
Listando portas abertas:
# # # # # # # # netstat -an | grep LISTEN lsof -i # Linux Lista todas as conexes de Internet socklist # Linux Mostra lista de sockets abertos sockstat -4 # FreeBSD Lista Aplicaes netstat -anp --udp --tcp | grep LISTEN # Linux netstat -tup # Lista conexes ativas de/para sistemas (Linux) netstat -tupl # Lista portas em escuta do sistema (Linux) netstat -ano # Windows

F ir e w al l
Verificando se o firewall esta executando. Linu x
# iptables -L -n -v Open the iptables firewall # iptables -P INPUT ACCEPT # iptables -P FORWARD ACCEPT # iptables -P OUTPUT ACCEPT # iptables -Z regras # iptables -F # iptables -X # Status # Abre tudo # Zera os contadores de pacotes p ara todas as # Limpa todas as Regras # Deleta todas as Regras

FreeBS D
# ipfw show # Status

# ipfw list 65535 # if answer is "65535 deny ip from any to # sysctl net.inet.ip.fw.enable=0 # Disable # sysctl net.inet.ip.fw.enable=1 # Enable

any" the fw is disabled

Enc a m i n h a m e nt o IP p ar a Rot e a m e n t o
Linu x Verifica e habilita o encaminhamento do IP com:
# cat /proc/sys/net/ipv4/ip_forward # Verifica o # echo 1 > /proc/sys/net/ipv4/ip_forward IP encaminhado 0=off, 1=on

ou edita /etc/sysctl.conf com:


net.ipv4.ip_forward = 1

FreeBS D Verifica e habilita com:


# sysctl net.inet.ip.forwarding # Verifica o IP encaminhado 0=off, 1=on # sysctl net.inet.ip .forwarding=1 # sysctl net.inet.ip.fastforwarding=1 # Para dedicao do roteador ou firewall Permanencia com entrada em /etc/rc.conf: gateway_enable="YES" # Defina como YES se essa mquina for um gateway.

Solaris
# ndd -set /dev/ip ip_forwarding 1 # Defina o IP para o encaminhamento 0=off, 1=on

N A T N e t w or k A d dr e s s Tr a ns l a ti on
Linu x
# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE # Para ativar o NAT # iptables -t nat -A PREROUTING -p tcp -d 78.31.70.238 --dport 20022 -j DNAT \ --to 192.168.16.44:22 # Port forward 20022 to internal IP port ssh # iptables -t nat -A PREROUTING -p tcp -d 78.31.70.238 --dport 993:995 -j DNAT \ --to 192.168.16.254:993 -995 # Port forward of range 993 -995 # ip route flush cache # iptable s -L -t nat # Check NAT status

Deleta a porta para o encaminhamento com -D em vez de -A. FreeBS D


# natd -s -m -u -dynamic -f /etc/natd.conf -n fxp0 Ou edita /etc/rc.conf com: firewall_enable="YES" # Defina YES para ativar a funo do firewall firewall_type="open" # Tipo de firewall (veja /etc/rc.firewall) natd_enable="YES" # Habilite natd (if firewall_enable == YES). natd_interface="tun0" # Interface pblica ou endereo de IP para uso. natd_flags=" -s -m -u -dynamic -f /etc/natd.conf"

Porta em encaminhada com:

# cat /etc/natd.conf same_ports yes use_sockets yes unregistered_only # redirect_port tcp insideIP:2300 -2399 3300 -3399 redirect_port udp 192.168.51.103:7777 7777

# Faixa de porta

D NS

No Unix o DNS so vlidos para todas as interfaces e armazenadas no /etc/resolv.conf. O domnio para qual a mquina pertence tambm armazenado no arquivo. A configurao mnima :
nameserver 78.31.70.238 search sleepyowl.net intern.lab domain sleepyowl. net # hostname -d

Verifica o nome do domnio no sistema com:


# Igual ao dnsdomainname

Windo ws No Windows o DNS so configurados pela interface. Para que exiba a configurao DNS e para limpar o cache do DNS usa-se:
# ipconfig /? # ipconfig /all # Exibe ajuda # Veja toda a informao incluindo o DNS

Lim pa o DNS Limpe o cache DNS do SO, alguns aplicativos usa seu prprio cache (ex. Firefox).
# # # # /etc/init.d/nscd restart lookupd -flushcache dscacheutil -flushcache ipconfig /flushdns # # # # Reinicia ns cd, se utilizar - Linux/BSD/Solaris OS X Tiger OS X Leopard and newer Windows

En caminhe as Consu ltas Faa um teste de configurao com seu amigo. Por exemplo o servidor DNS pblico 213.133.105.2 ns.second -ns.de pode ser usado para teste. Veja como o servidor cliente responde isso (uma simples resposta).
# dig sleepyowl.net sleepyowl.net. 600 IN A ;; SERVER: 192.168.51.254#53(192.168.51.254) 78.31.70.238

O roteador 192.168.51.254 respondeu e responsvel pela entrada do A. Pouca entrada pode ser requerida e o servidor de DNS pode selecionar com @:
# # # # dig dig dig dig MX google.com @127.0.0.1 NS sun.com @204.97.212.10 NS MX heise.de AXFR @ns1.xname.org cb.vu # Para te ste o local do servidor # Consulta externa do servidor # Obtenha a zona cheia(zona de transferncia) # Obtenha o mail MX de entrada # Obtenha o NS da conexo TCP. # Obtenha qualquer coisa

O programa da mquina tambm poderoso.


# host -t MX cb.vu # host -t NS -T sun.com # host -a sleepyowl.net

Consultas In ve rsas Encontra o nome coletivo para o endereo de IP (in -addr.arpa). Isso pode ser feito dig, host e nslookup :
# dig -x 78.31.70.238 # host 78.31.70.238 # nslookup 78.31.70.238

/e tc/hos ts Mquinas individuais podem ser configuradas no arquivo /etc/hosts ao contrrio de executar localmente para resolver as consultas do nome da mquina. O formato simples, por exempl
78.31.70.238 sleepyowl.net sleepyowl

A prioridade entre as mquinas e as consultas dns, a ordem das consultas de resoluo de nomes, podem ser configuradas no /etc/nsswitch.conf e /etc/host.conf. O arquivo existente do Windows, normalmente no:
C:\WINDOWS\SYSTEM32\DRIVERS\ETC

D H CP
Linu x Algumas distribuies (SuSE) usa dhcpcd como cliente. O padro eth0.
# dhcpcd -n eth0 # dhcpcd -k eth0 # Provocar uma renovao( no sempre funciona) # lanamento e encerramento

O arrendamento com a total informao so armazenadas no:


/var/lib/dhcpcd/dhcpcd -eth0.info

FreeBS D FreeBSD (e Debian) usa dhclient. Para configurar a interface (por exemplo bge0) executa:
# dhclient bge0

O arrendamento com a total informa o so armazenados no:


/var/db/dhclient.leases.bge0

Usa
/etc/dhclient.conf

para preceder as opes ou forar as diferentes opes:


# cat /etc/dhclient.conf interface "rl0" { prepend domain -name-servers 127.0.0.1; default domain -name "sleepyowl.net"; supersede domain -name "sleepyowl.net"; }

Windo ws O dhcp pode ser renovado com ipconfig :


# ipconfig /renew # ipconfig /renew LAN # ipconfig /release WLAN # renova todos os adaptadores # renew the adapter named "LAN" # release the adapter named "WLAN"

Sim isto uma boa idia para renomear seu adaptador com simples nomes!

A n l is e d e Tr feg o
Bmonhttp://people.suug.ch/~tgr/bmon/ um pequeno console da largura de bandas e pode exibir o fluxo de diferentes interfaces. Sniff com tcpdump
# tcpdump # tcpdump # tcpdump # tcpdump # tcpdump file # tcpdump file # tcpdump # tcpdump # tcpdump # tcpdump # tcpdump # tcpdump -nl -i bge0 not port ssh and src \(192.168.16.121 or 192.168.16.54 \) -n -i eth1 net 192.168.16 .121 # select to/from a single IP -n -i eth1 net 192.168.16.0/24 # select traffic to/from a network -l > dump && tail -f dump # Buffered output -i rl0 -w traffic.rl0 # Write t raffic headers in binary -i rl0 -s 0 -w traffic.rl0 -r traffic.rl0 port 80 host google.com -i eth0 -X port \(110 or 143 \) -n -i eth0 icmp -i eth0 -s 0 -A port 80 | grep GET # Write traffic + payload in binary # Read from file (also for ethereal # The two classic commands # Check if pop or imap is secure # Only catch pings # -s 0 for full packet -A for ASCII

Adiciona importante opes:


y y y -A -X -l

Imprime cada pacotes na limpeza do texto (sem cabealho) Imprime pacotes em hex e ASCII Faa a linha de sada do buffer

-D

Imprime todas as interfaces disponveis

No Windows usa o windump www.winpcap.org. Usa windump -D para listar as interfaces. S can com nmap Nmaphttp://insecure.org/nmap/ a porta scanner com SO, isto normalmente so instalados nas distribuies e tambm esto disponveis para windows. Se voc no scan seus servidores, hackers fazem isso para voc...
# nmap cb.vu # scans todas porta s reservadas TCP na mquina # nmap -sP 192.168.16.0/24 # Procura IP de fora e so usados pela mquina na mquina 0/24 # nmap -sS -sV -O cb.vu # Faz a descrio SYN scan com a verso e SO detectadas PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 3.8.1p1 FreeBSD -20060930 (protocol 2.0) 25/tcp open smtp Sendmail smtpd 8.13.6/8.13.6 80/tcp open http Apache httpd 2.0.59 ((FreeBSD) DAV/2 PHP/4. [...] Running: FreeBSD 5.X Uptime 33.120 days (since Fri Aug 31 11:41:04 2007) Outro padro mais usados so as ferramentas hping (www.hping.org) um pacote IP assembler/analyzer e fping (fping.sourceforge.net). fping pode checar multiplos rund -robin

fashion.

Con tr ol e d e tr fe g o (Q oS )
Controle de trfego gerencia a fila, polcia, programao e outros parmetros de trfego para uma rede. Os exemplos seguintes so simples usos prticos do Linux e FreeBSD capacidades para uma melhor utilizao da largura de banda disponvel. limite upload Limite de upload Modens DSL ou de cabo tm uma longa fila para melhorar o rendimento upload. No entanto preenchendo a fila com um dispositivo rpido (ethernet, por exemplo) ir diminuir drasticamente a interatividade. Por conseguinte, til para limitar a taxa de upload dispositivo para coincidir com a capacidade fsica do modem, isso deve melhorar muito a interatividade. Situado a cerca de 90% da mxima modem (cabo) de velocidade. Linux Para a 512 Kbit upload modem.
# # # # tc tc tc tc qdisc add dev eth0 root tbf rat e 480kbit latency 50ms burst 1540 -s qdisc ls dev eth0 # Status qdisc del dev eth0 root # Delete the queue qdisc change dev eth0 root tbf rate 220kbit latency 50ms burst 1540

Free BSD FreeBSD usa o dummynet trfego afiado que so configurados ipfw. Tubos so usados para aumentar seus limites da largura da banda na nica do[K|M]{bit/s|Byte/s}, 0 meios ilimitados. Usando igual ao nmero do tubo reconfigurar isto. Por exemplo o limite do upload da largura da banda para 500 Kbit.
# kldload dummynet # ipfw pipe 1 config bw 500Kbit/s largura da banda # ipfw add pipe 1 ip from me to any tubo # carrega os mdulos se necessrio # cria um tubo com limitado pela # diverte todos os upload tambm pelo

Qualidade de Se rvio Linux

# # # # #

tc qdisc add dev eth0 root handle 1: prio priomap 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 0 tc qdisc add dev eth0 parent 1:1 handle 10: sfq tc qdisc add dev eth0 parent 1:2 handle 20: sfq tc qdisc add dev eth0 parent 1:3 handle 30: sfq tc filter add dev eth0 protocol ip parent 1: prio 1 u32 \ match ip dport 10000 0x3C00 flowid 1:1 # usa a faixa de portas para os servidores match ip dst 123.23.0.1 flowid 1:1 # e/ou usa IP do servidor

Prioridade nas filas com tc para otimizar VoIP. Veja o total exemplo no voip-info.org ou www.howtoforge.com. Suposto VoIP usados udp na porta 10000:11024 e dispositivos eth0 (tambm poderia ser ppp0 ou assim). Seguindo os comandos define o QoS para as filas das rvores e fora o trfego VoIP para as filas The following commands com QoS 0x1e (todos os bits). O padro do fluxo em 3 filas e QoS Mnimo-atraso fluxo em 2 filas.

Status and remove with


# tc -s qdisc ls dev eth0 # tc qdisc del dev eth0 root # status da fila # deleta todos QoS

Calcula a faixa das portas e a mscara O filtro tc define a faixa das portas e a mscara que voc calculou. Encontra o 2^N finalizando a faixa da porta, deduzi a faixa e converte para HEX. Essa a sua mscara. Exemplo para 10000 -> 11024, a faixa 1024.
# 2^13 (8192) < 10000 < 2^14 (16384) # echo "obase=16;(2^14) -1024" | bc # finalizando 2^14 = 16384 # mask is 0x3C00

Free BSD O max largura da banda 500Kbit/s e ns definimos 3 filas com a prioridade 1 00:10:1 para VoIP:ssh:all the rest.
# # # # # # # # ipfw ipfw ipfw ipfw ipfw ipfw ipfw ipfw pipe 1 config bw 500Kbit/s queue 1 config pipe 1 weight 100 queue 2 config pipe 1 weight 10 queue 3 config pipe 1 weight 1 add 10 queue 1 proto udp dst -port 10000 -11024 add 11 queue 1 proto udp dst -ip 123.23.0.1 # e/ou usa o IP do servidor add 20 queue 2 dsp -port ssh add 30 queue 3 from me to any # reinicia todos # status das regras # status do tubo # deleta todas as regras por padro

Status e remove com


# ipfw list # ipfw pipe list # ipfw flush

NI S D e b u g gi ng
Alguns comandos que deveria trabalhar ser bem configuradas NIS cliente:
# # # # # ypwhich domainname ypcat group cd /var/yp && make rpcinfo -p servername # Obtem a conexo NIS do servidor de nomes # Configura o nome do domnio NIS # Mostra o grupo do servidor NIS # Reconstri o yp banco de dados # Relatrio de servio RPC do servidor

Est ypbind executando?


# ps auxww | grep ypbind /usr/sbin/ypbind -s -m -S servername1,servername2 # FreeBSD /usr/sbin/ypbind # Linux # yppoll passwd.byname Mapeia o passwd.byname tm outro nmero 11 90635041. Seg Sep 24 13:57:21 2007 O servio master servername.domain.net.

Linu x
# cat /etc/yp.conf ypserver nomeservidor domain domain.net broadcast

N et c a t
Netcathttp://netcat.sourceforge.net (nc) o melhor conhecido como "network Swiss Army Knife", isto pode ser manipulado, cria ou l/escreve TCP/IP coneces. Aqui so usados alguns exemplos, l alguns mais no net, por exemplo g-loaded.eu[...]http://www.gloaded.eu/2006/11/06/netcat-a-couple-of-useful-examples e herehttp://www.terminallyincoherent.com/blog/2007/08/07/few-useful-netcat-tricks. Voc precisa usar comandos netcat em vez de nc. Tambm veja um comando similar socat. Trans fe r ncia de arquivo Copia a largura do diretrio sobre uma conexo. A transferncia muito rpido (no em cima do protocolo) e voc no precisa para bagunar com NFS ou SMB ou FTP ou ento, faa um simples arquivo avaliado no servidor, e coloque isso no cliente. Aqui 192.168 .1.1 o endereo do servidor.
server# tar -cf - -C VIDEO_TS . | nc -l -p 4444 servidor 4444 client# nc 192.168.1.1 4444 | tar xpf - -C VIDEO_TS server# cat largefile | nc -l 5678 client# nc 192.168.1.1 5678 > largefile server# dd if=/dev/da0 | nc -l 4444 client# nc 192.168.1.1 4444 | dd of=/dev/da0 client# nc 192.168.1.1 4444 | dd of=da0.img arquivo # Diretrio tar na porta do # Puxa o arquivo na porta 4444 # O nico arquivo # Puxa o nico arquivo # Imagem da partio # Puxa a partio para o clone # Puxa a partio para o

Outros hacks Especialmente aqui, voc conhece mais do que voc faz. Shell remota Opo -e somente para a verso Windows? Ou usa nc 1.10.
# nc -lp 4444 -e /bin/bash clandestino) # nc -lp 4444 -e cmd.exe # Fornece um shell remoto (servidor # shell remoto para Windows

Se rvidor de eme rgncia web Servidor nico arquivo na porta 80 no loop.


# while true; do nc -l -p 80 < unixtoolbox.xhtml; done

Bate-papo Alice e Bob pode conversar com um socket TCP simples. O texto transferido com a chave de entrada.
alice# nc -lp 4444 bob # nc 1 92.168.1.1 4444

SSH SCP
Chave Pblica | Fingerprint | SCP | Tunelamento

A ut e n ti c a o p or c h av e p bl i c a
Conecte na mquina sem senha utilizando a autenticao por chave pblica. A idia acrescentar sua chave pblica para a authorized_keys2 arquivo na mq uina remota. Para isso veja o exemplo: conecte mquina-cliente para mquina-servidor, a chave gerada no cliente. Com cygwin voc poderia ter criada em sua casa um diretrio e o diretrio do .ssh utilizando # mkdir -p /home/USER/.ssh

y y

Usa ssh-keygen para gerar o par de chaves. ~/.ssh/id_dsa is the private key, ~/.ssh/id_dsa.pub chave pblica. Copia somente a chave pblica para acrescentar o arquivo no servidor ~/.ssh/authorized_keys2 em sua casa no servidor.

# ssh-keygen -t dsa -N '' # cat ~/.ssh/id_dsa.pub | ssh you@host -server "cat - >> ~/.ssh/authorized_keys2"

Utilizan do o clien te Win dows ssh. com A verso no comercial do cliente ssh.com pode ser feito o download no site ftp: ftp.ssh.com/pub/ssh/. Chaves geradas pelo cliente ssh.com precisa ser convertido para o servidor OpenSSH. Isso pode ser feito com o comando ssh-keygen
y y y y y y y

Cria o par de chaves com o cliente ssh.com: Configuraes - Autenticao do Usurio Gerar Novo... Eu uso o tipo de chave DSA; comprimento da chave 2048. Copia a gera chave pblica pelo ssh.com cliente para o servidor tambm o ~/.ssh diretrio. As chaves esto no C:\Documents and Settings\%USERNAME%\Application Data\SSH\UserKeys. Usa o comando ssh-keygen no servidor para converter a chave:
# cd ~/.ssh # ssh-keygen -i -f keyfilename.pub >> authorized_keys2

Aviso: Ns usamos a chave DSA, RSA tambm possvel. A chave no protegida por senha. Us ando o putty para Win dows Puttyhttp://www.chiark.greenend.org.uk/~sgtatham/putty/download.html simples e livre o cliente ssh para Windows.
y y y

Cria o par de chaves com o programa puTTYgen. Salve a chave pblica (por exemplo em C: \Documents and Settings\%USERNAME%\.ssh). Copia a chave pblica para o servidor no ~/.ssh folder:
# scp .ssh/puttykey.pub root@192.168.51.254:.ssh/

y y y y

Usa o comando ssh-keygen no servidor para converter a chave para O penSSH:


# cd ~/.ssh # ssh-keygen -i -f puttykey.pub >> authorized_keys2

Ponto da chave privada localizada nas configuraes putty: Conexo - SSH - Auth

Ch e c a fin g er pr i n t
No primeiro login, ssh perguntar se a mquina for desconhecida com o fingerprint te m que ser armazenada no na mquina desconhecida. Para evitar um man -in-the-middle ataque o administrador do servidor pode ser enviado para seu servidor fingerprint que comparado no primeiro login. Usa ssh-keygen -l para obter o fingerprint (no servidor):
# ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub # Para chave RSA 2048 61:33:be:9b:ae:6c:36:31:fd:83:98:b7:99:2d:9f:cd /etc/ssh/ssh_host_rsa_key.pub # ssh-keygen -l -f /etc/ssh/ssh_host_dsa_key.pub # Para DSA (padro) 2048 14:4a:aa:d9:73:25:46:6d:0a:48:35:c7:f4:16:d4:ee /etc/ssh/ssh_host_dsa_key.pub

Agora o cliente se conectar a esse servidor, pode verificar que ele est se conectando ao servidor direito:
# ssh linda A autenticao da mquina 'linda (192.168.16.54)' no pode ser estabelecida. Chave DSA fingerprint 14:4a:aa:d9:73:25:46:6d:0a:48:35:c7:f4:16:d4:ee.

Voc tem certeza que deseja continuar a conexo (sim/no)? sim

Tr a ns fer n ci a s e g ur a d e ar q uiv os
Alguns comandos simples:
# scp file.txt host -two:/tmp # scp joe@ host-two:/www/*.html /www/tmp # scp -r joe@host -two:/www /www/tmp

No Konqueror ou Midnight Commander isso possvel para o acesso do sistema remoto com o endereo fish://user@porta. Entretanto a implementao muito lenta. Alm disso possvel para montar o diretrio remoto com sshfs um sistema de arquivo baseada no SCP. Veja sshfshttp://fuse.sourceforge.net/sshfs.html.

Tu n e l a m e nt o
Tunelamento SSH permite o encaminhamento ou reverte para frente de uma porta atravs da conexo SSH, garantindo assim o trfego e o acesso das portas que de outra fora so bloqueadas. Isso s com TCP. A nomenclatura geral para o encaminhamento e o reverso (veja tambm ssh and NAT example):
# ssh -L localport:desthost:destport user@gate # desthost como pode ser visto a partir do porto # ssh -R destport:desthost:localport user@gate # porta loca l encaminha para o seu destino # desthost: localport como pode ser visto a partir do cliente do incio do tnel # ssh -X user@gate # Para forar encaminhamento X

Este conectar na porta e encaminhar a porta local para a mquina desthost: destport. N ota desthost a mquina de destino como pode ser visto pela porta, ento se a conexo para a porta, ento o desthost o localhost. Mais do que uma porta para o encaminhamento possvel. En caminha direto para a po rta Vamos dizer que ns queremos acessar o CVS (porta 2401) e http (porta 80) que esto executando na porta. Esse simplesmente exemplo, na mquina destino assim a mquina local, e ns usamor a porta 8080 localmente instanciada de 80 por isso no precisa se r o root. Primeiro a sesso ssh aberta, ambos os services so acessveis nas portas locais.
# ssh -L 2401:localhost:2401 -L 8080:localhost:80 usuario@porta

Ne tbios e desktop remoto e ncaminham para um se gun do se rvido r Vamos dizer que um servidor smb Wind ows a porta est por trs e no est executando o ssh. Ns precisamos de acesso ao compartilhamento SMB e desktop remoto tambm para o servidor. O compartilhamento SMB pode agora ser acessado com \\127.0.0.1\, mas somente se o local do compartilhamento desabilitado, porque o local do compartilhamento ouvido na porta 139. Isto possvel para manter o local compartilhado habilitado, para isso ns precisamos criar um novo dispositivo virtual c om um novo endereo IP para o tunelamento, o compartilhamento smb conectar atravs do endereo. Alm disso o local RDP est pronto para ser ouvido na porta 3389 , ento ns escolhemos 3388. Para isso vamos usar um IP virtual 10.1.1.1.
y # ssh -L 139:smbserver:139 -L 3388:smbserver:3389 usuario@porta

Com putty usa-se Origem porta=10.1.1.1:139. possvel a criao mltipla de dispositivos de loop e o tnel. No Windows 2000, somente putty funcionou comigo. No Windows Vista tambm encaminhar a porta 445 na adio para a porta 139. Tambm no Vista o pacote KB942624 impede a porta 445 para ser encaminhada, ento eu tive que desinstalar esse pacote no Vista.

Com o cliente ssh.com, desabilite "Permite somente conexo local". Desde que ssh.com vincular todos os endereos, apenas uma parte nica pode ser conectado.

Agora cria a interface loopback com o IP 10.1.1.1:


y y y y y

# Sistema->Painel de Controle->Adicionar Hardware # Sim, Hardware est pronto para ser conectado # Adiciona um novo hardware (em baixo). # Instala o hardware que manualmente selecionado # Adaptador de Rede # Microso ft , Microsoft Adaptador Loopback. Configura o endereo IP do dispositivo falso para 10.1.1.1 mask 255.255.255.0, sem gateway. avanado->WINS, Habilita LMHosts Lookup; Desabilita NetBIOS sobre TCP/IP. # Habilita Cliente para Microsoft redes. # Desabilit a compartilhamento de arquivo e impressora para a rede Microsoft.

Tive que reiniciar para esse trabalho. Agora conecta para o compartilhamento com \\10.1.1.1 e o desktop remoto para 10.1.1.1:3388. De bug Se no funcionar
y y y y

So as portas encaminhadas: netstat -an? Veja isto 0.0.0.0:139 ou 10.1.1.1:139 Faz telnet 10.1.1.1 139 conectado? Voc precisa checar o box "Portas local aceita conexes de outras mquinas". o "Compartilhamento de arquivo e impressora para redes Micro soft" desabilitou na interface loopback?

conexo de dois clientes atrs do NAT Suponhamos dois clientes esto fazendo o gateway NAT e o cliente cliadmin tm conexo para cliente cliusuario (destino), ambos podem logar para a porta com ssh e so executados no Linux com sshd. Voc no precisar ter acesso root em nenhum lugar desde que as portas do porto esto acima de 1024. Ns usamos 2022 na porta. Tambm porque a porta usada localmente, a opo GatewayPorts no necessrio. No cliente cliusuario (de destino para a porta):
# ssh -R 2022:localhost:22 usuario@porta porta: 2022 # encaminha o cliente 22 para a

No cliente cliadmin (da mquina da porta):


# ssh -L 3022:localhost:2022 admin@porta porta:2022 # ssh -p 3022 admin@localhost cliente:22 # encaminha o cliente 3022 para a

Agora o administrador pode ligar diretamente para o cliente cliusuario com:


# local:3022 -> porta:2022 ->

Conecta com VNC po r trs do NAT Suponhamos um cliente Windows VNC escutando na porta 5900 tem que ter o acesso por trs do NAT. No cliente cliwin a porta:
# ssh -R 15900:localhost:5900 user@gate

On client cliadmin (from host to gate):


# vncconnect -display :0 localhost

# ssh -L 5900:localhost:15900 admin@gate

Agora o administrador pode conectar diretamente ao cliente VNC com: Escave um tnel ssh mu lti-ho p Suponhamos que voc no possa alcanar o servidor diretamente com ssh, mas somente atravs de vrias mquinas (por exemplo , por causa de questes de roteamento). s vezes,

ainda necessrio para obter um cliente direto - conexo com o servidor, por exemplo, para copiar arquivos com scp ou encaminhar outras portas como SMB ou VNC. Uma maneira de fazer isso a cadeia de tneis em conjunto para avanar com uma porta para o servidor ao longo do lpulo. Este transportador porto s chega ao seu destino final na ltima conexo com o servidor. Suponha que queremos transmitir a porta SSH a partir de um cliente para um servidor mais de dois saltos. Uma vez que o tnel construdo, possvel se conectar ao servidor diretamente do cliente (e tambm adiciona outra porta para o encaminhamento). Criando tnel no shell cliente -> maquina1 -> maquina2 -> servidor e escavar tnel 5678
cliente># ssh -L5678:localhost:5678 mquina1 o tnel maquina_1># ssh -L5678:localhost:5678 mquina2 a mquina2 maquina_2># ssh -L5678:localhost:22 servidor servidor # 5678 uma porta arbitraria para # sequncia 5678 da mquina1 para # No final do tnel na porta 22 no

Utilizando tnel com outro shell cliente -> usando o tnel 5678 no servidor
# ssh -p 5678 localhost # conecta diretamente do cliente para o servidor # scp -P 5678 myfile localhost:/tmp/ # o u copia o arquivo diretamente utilizando o tnel # rsync -e 'ssh -p 5678' myfile localhost:/tmp/ # ou rsync o arquivo diretamente para o servidor

Au tocon nect script e man te r vivo Eu uso as variaes do script a seguir para manter uma mquina alcanveis por um tnel SSH reverso. A conexo automaticamente reconstruda se fechado. Voc pode adicionar vrios -L or -R tneis em uma linha.
#!/bin/sh COMMAND="ssh -N -f -g -R 3022:loca lhost:22 colin@cb.vu" pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND exit 0 1 * * * * colin /home/colin/port_forward.sh # crontab entrada (aqui a cada hora)

VPN C OM SSH
A partir da verso 4.3, o OpenSSH pode usar o dispositivo tun/tap para encriptar um tunnel. Isto muito semelhante a outras solues VPN baseada em TLS como o OpenVPN. Uma vantagem com o SSH que no h a necessidade de instalar e configurar um software adcional. Alm disso o tunel utiliza a autenticao SSH como a chave compartilhada. A desvantagem que o encapsulamento feito atravs do TCP que poderiam resultar em um desempenho ruim em um link lento. Alm disso, o tnel est confiando em uma nica conexo TCP (frgil). Esta tcnica muito til para a configurao rpida de uma VPN baseada em IP. No h nenhuma limitao quanto nica porta TCP, todas os protocolos de camadas 3/4 como o ICMP, TCP/UDP, etc so transmitidos atravs da VPN. Em qualquer caso, as seguintes opes so necessrias no arquivo sshd_conf:
PermitRootLogin yes PermitTunnel yes

Con e x o P2 P ni c a
Aqui estamos conectando dois hosts, e hclient hserver com um tnel peer to peer. A conexo started from hclient para o hserver feito como root. Os pontos de extremidade do tnel

so 10.0.1.1 (servidor) e 10.0.1.2 (cliente) e criamos um dispositivo tun5 (isso tambm poderia ser um outro nmero). O procedimento muito simples:
y y

Conectar com SSH usando o tnel, opo -w Configure os endere os IP do tnel. Uma vez no servidor e uma vez o cliente.

Conectar ao se rvido r Conexo iniciada no cliente e os comandos so executados no servidor. Linux o Se rvidor
cli># ssh -w5:5 root@hserver srv># ifconfig tun5 10.0.1.1 netmask 255.255.255.252 # Executada no shell do servidor

Free BSD o Se rvidor


cli># ssh -w5:5 root@hserver srv># ifconfig tun5 10.0.1.1 10.0.1.2 # Executada no shell do servidor

Con figu re o Cliente Comandos executados no cliente:


cli># ifconfig tun5 10.0.1.2 netmask 255.255.255.252 cli># ifconfig tun5 10.0.1.2 10.0.1.1 # Cliente um Linux # Cliente um FreeBSD

Os dois hosts esto conectados de forma transparente e podem se comunicar com qualquer protocolo de camada 3/4 usando os endereos IP do tnel.

Con e ct a r D u as Re d e s
Alm da instalao p2p acima, mais til conectar duas redes provadas com uma VPN SSH usando dois gateways. Supondo o exemplo, netA 192.168.51.0/24 e netB 192.168.16.0/24. O procedimento semelhante ao citado acima, ns precisamos somente adicionar o roteamento. O NAT deve ser ativado na interface privada somente se os gateways no so padro da sua rede. 192.168.51.0/24 (netA)|gatewayA <-> gatewayB|192.168.16.0/24 (netB)
y y y y

Conectar com SSH usando o tnel, opo -w Configure os endereos IP do tnel. Uma vez no servidor e uma vez o cliente. Adicione o roteamento para as duas redes. Se necessrio, ative o NAT na interface privada do gateway.

A instalao started from gatewayA in netA. Conectar do GatewayA para o GatewayB A conexo iniciada a partir gatewayA e os comandos so executados em gatewayB Gate wayB o Linux
gatewayA># ssh -w5:5 root@gateB gatewayB># ifconfig tun5 10.0.1.1 netmask 255.255.255.252 # Executada no shell do GatewayB gatewayB># route add -net 192.168.51.0 netmask 255.255.255.0 dev tun5 gatewayB># echo 1 > /proc/sys/net/ipv4/ip_forward # Somente necessrio se o gateway no for padro gatewayB># iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Gate wayB o Free BSD


gatewayA># ssh -w5:5 root@gateB # Cria o dispositivo tun5

gatewayB># ifconfig tun5 10.0.1.1 10.0.1.2 GatewayB gatewayB># route add 192.168.51.0/24 10.0.1.2 gatewayB># sysctl net.inet.ip.forwarding=1 gateway n o for padro gatewayB># natd -s -m -u -dynamic -n fxp0 gatewayA># sysctl net.inet.ip.fw.enable=1

# Executada no shell do # Somente necessrio se o # veja NAT

Con figu re GatewayA Comando executado no GatewayA Gate wayA o Linux


gatewayA># gatewayA># gatewayA># gatewayA># ifconfig tun5 10.0.1.2 netmask 255.255.255.252 route add -net 192.168.16.0 netmask 255.255.255.0 dev tun5 echo 1 > /proc/sys/net/ipv4/ip_forward iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Gate wayA o Free BSD


gatewayA># gatewayA># gatewayA># gatewayA># gatewayA># ifconfig tun5 10.0.1.2 10.0.1.1 route add 192.168.16.0/24 10.0.1.2 sysctl net.inet.ip.forwarding=1 natd -s -m -u -dynamic -n fxp0 sysctl net.inet.ip.fw.enable=1

# veja NAT

Agora as duas redes privadas esto conectadas transparentemente via VPN SSH. O NAT soemten necessrio se os gateways no forem o padro da rede. Neste caso os clientes no sabem para onde encaminhar a re sposta,e o nat dever ser ativado.

RSYNC
Rsync quase pode substituir completamente o cp e scp, alm disso, se interromper as transferncias so eficientemente reiniciado. A pgina do manual boa... Aqui alguns Exemplos: Copia o contedo completo do diretrio:
# rsync -a /home/colin/ /backup/colin/ # rsync -a /var/ /var_bak/ # rsync -aR --delete-during /home/user/ /backup/ abaixo) # modo "arquivo". manter o mesmo # utilizao relativa (veja

Mesmo que a anterior, porm sobre a rede com com compresso. O Rsync usa o SSH por padro para o transporte e usar as chaves ssh se for definido. Use ":" como o SCP. Uma tpica cpia remota:
# rsync -axSRzv /home/user/ user@server:/backup/user/ # Cpia remota # rsync -a 'user@server:My \ Documents' My \ Documents # Simula a cpia para uma shell remota

Excluir qualquer diretrio tmp dentro de /home/user/ e manter a hierarquia de pastas relativa, que o diretrio remoto ter a estrutura /backup/home/user/. Isto tipica mente usado para backups.
# rsync -azR --exclude=tmp/ /home/user/ user@server:/backup/

Usa a porta 20022 para a conexo ssh:


# rsync -az -e 'ssh -p 20022' /home/colin/ user@server:/backup/colin/

Usando o daemon rsync (usado com "::") muito rpido, por m no encriptografados por ssh. A localizao do /backup definido pela configurao em /etc/rsyncd.conf. A varivel RSYNC_PASSWORD pode ser ajustado para evitar a necessidade de digitar a senha manualmente.
# rsync -axSRz /home/ ruser@hostname::rmodule/backup/ # rsync -axSRz ruser@hostname::rmodule/backup/ /home/ # Para copiar de volta

Algumas opes importantes:


y y -a, --archive -r, --recursive

modo arquivo; mesmo que -rlptgoD (sem -H) recursivo em diretrios

y y y y y y y

-R, --relative usar nome de diretrios relativo -H, --hard-links preserva os links -S, --sparse manipula os arquivos de forma eficiente -x, --one-file-system no atravessa o limite do sistema de arquivos --exclude=PATTERN Exclui os arquivos padres --delete-during exclui receptor durante xfer, no antes --delete-after exclui receptor aps a transferncia, no antes

Rs y n c e m W i n d ow s
Rsync est disponvel para Windows atravs do Cygwin ou empacotado em cwrsynchttp://sourceforge.net/projects/sereds. Isto muito conveniente para backups automatizados. Instalar um deles (not both) e adicione o caminho para as variveis do sistema Windows: # Painel de controle -> Sistema -> aba Avanado, boto Variveis de Ambiente. Edite a "Pasta" variveis de sistema e adicione o caminho completo para o rsync instalado, exemplo: C: \Program Files\cwRsync\bin ou C:\cygwin\bin. Desta forma os comandos rsync e ssh esto disponveis no shell do Windows. Au tenticao via Chave Pblica Rsync automaticamente encapsulada por SSH e, portanto, usa a autenticao no servidor SSH. os backups automticos para evitar a interao do usurio usa autenticao SSH via chave pblica e pode ser usado o comando rsync que ser executado sem uma senha. Todos os seguintes comandos so executados dentro de um console do Windows. Em um console (Iniciar -> Executar -> cmd) crie e carregue a chave conforme descrito no SSH, altere o "user" e "server" as appropriate. If the file authorized_keys2 does not exist yet, simply copy id_dsa.pub to authorized_keys2 and upload it.conforme o caso. Se o arquivo authorized_keys2 ainda no existe, basta copiar id_dsa.p ub para authorized_keys2 e carreg-lo.
# # # # # ssh-keygen -t dsa -N '' rsync user@server:.ssh/authorized_keys2 . cat id_dsa.pub >> authorized_keys2 rsync authorized_keys2 user@server:.ssh/ del authorized_keys2 # Cria a chave pblica e privada # Copia o arquivo localmente do server # Ou usar um editor para adicionar a chave # Copia o arquivo de volta para o server # Remove a cpia local

Agora teste com (em uma linha):


rsync -rv "/cygdrive/c/Documents and Set tings/%USERNAME%/My Documents/" \ 'user@server:My \ Documents/'

Backup Automtico Use um arquivo em lotes para automatizar o backup e adicionar o arquivo nas tarefas agendadas (Programas -> Acessrios -> Ferramentas do Systema -> Tarefas Agendadas). Por exemplo crie o arquivo backup.bat e substitua user@server.
@ECHO OFF REM rsync o diretrio My Documents SETLOCAL SET CWRSYNCHOME=C: \PROGRAM FILES \CWRSYNC SET CYGWIN=nontsec SET CWOLDPATH=%PATH% REM descomente a linha seguinte, se usar cygwin SET PATH=%CWRSYNCHOME% \BIN;%PATH% echo Pressione Control -C para Abortar rsync -av "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" 'user@server:My \ Documents/' pause

SUDO

Sudo is a standard way to give users some administrative rights without giving out the root password. Sudo is very useful in a multi user environment with a mix of server and workstations. Simply call the command with sudo:
# sudo /etc/init.d/dhcpd restar t # sudo -u sysadmin whoami # Run the rc script as root # Run cmd as an other user

Con fi g ur a ti on
Sudo is configured in /etc/sudoers and must only be edited with visudo. The basic syntax is (the lists are comma separated):
user hosts = (runas) commands y y y y # In /etc/sudoers users one or more users or %group (like %wheel) to gain the rights hosts list of hosts (or ALL) runas list of users (or ALL) that the command rule can be run as. It is enclosed in ( )! commands list of commands (or ALL) that will be run as root or as (runas)

Additionally those keywords can be defined as alias, they are called User_Alias, Host_Alias, Runas_Alias and Cmnd_Alias. This is useful for larger setups. Here a sudoers example:
# cat /etc/sudoe rs # Host aliases are subnets or hostnames. Host_Alias DMZ = 212.118.81.40/28 Host_Alias DESKTOP = work1, work2 # User aliases are a User_Alias ADMINS User_Alias DEVEL Runas_Alias DBA list of users which can have the same rights = colin, luca, admin = joe, jack, julia = oracle,pgsql

# Command aliases define the full path of a list of commands Cmnd_Alias SYSTEM = /sbin/reboot,/usr/bin/kill,/sbin/halt,/sbin/shutdown,/etc/init.d/ Cmnd_Alias PW = /usr/bin/passwd [A -z]*, !/usr/bin /passwd root # Not root pwd! Cmnd_Alias DEBUG = /usr/sbin/tcpdump,/usr/bin/wireshark,/usr/bin/nmap # The actual rules root,ADMINS ALL = (ALL) NOPASSWD: ALL # ADMINS can do anything w/o a password. DEVEL DESKTOP = (ALL) NOPASSWD: ALL # Developers have full right on desktops DEVEL DMZ = (ALL) NOPASSWD: DEBUG # Developers can debug the DMZ servers. # User sysadmin can mess around in the DMZ servers with some commands. sysadmin DMZ = (ALL) NOPASSWD: SYSTEM,PW,DEBUG sysadmin ALL,!DMZ = (ALL) NOPASSWD: ALL # Can do anything outside the DMZ. %dba ALL = (DBA) ALL # Group dba can run as database user. # anyone can mount/unmount a cd -rom on the desktop machines ALL DESKTOP = NOPASSWD: /sbin/mount /cdrom,/sbin/umount /cdrom

ENCRYPT FILES
O p en SS L
A sin gle file Encrypt and decrypt:
# openssl aes -128-cbc -salt -in file -out file.aes # openssl aes -128-cbc -d -salt -in file.aes -out file

Note that the file can of course be a tar archive. tar an d en crypt a whole dire cto ry
# tar -cf - directory | openssl aes -128-cbc -salt -out directory.tar.aes # Encrypt

# openssl aes -128-cbc -d -salt -in directory.tar.aes | tar -x -f -

# Decrypt

tar zip an d en crypt a whole dire cto ry


# tar -zcf - directory | openssl aes -128-cbc -salt -out directory.tar.gz.aes # openssl aes -128-cbc -d -salt -in directory.tar.gz.aes | tar -xz -f y y # Encrypt # Decrypt

Use -k mysecretpassword after aes-128-cbc to avoid the interactive password request. However note that this is highly insecure. Use aes-256-cbc instead of aes-128-cbc to get even stronger encryption. This uses also more CPU.

G PG
GnuPG is well known to encrypt and sign emails or any data. Furthermore gpg and also provides an advanced key management system. This section only covers files encryption, not email usage, signing or the Web -Of-Trust. The simplest encryption is with a symmetric cipher. In this case the file is encrypted with a password and anyone who knows the password can decrypt it, thus the keys are not needed. Gpg adds an extention ".gpg" to the encrypted file names.
# gpg -c file # gpg file.gpg # Encrypt file with password # Decrypt file (optionally -o otherfile)

Us ing keys For more details see GPG Quick Starthttp://www.madboa.com/geek/gpg-quickstart and GPG/PGP Basicshttp://aplawrence.com/Basics/gpg.html and the gnupg documentationhttp://gnupg.org/documentation among others. The private and public keys are the heart of asymmetric cryptography. What is important to remember:
y

Your public key is used by others to encrypt files that only you as the receiver can decrypt (not even the one who encrypted the file can decrypt it). The public key is thus meant to be distributed. Your private key is encrypted with your passphrase and is used to decrypt files which were encrypted with your public key. The private key must be kept secure. Also if the key or passphrase is lost, so are all the files encrypted with your public key. The key files are called keyrings as they can contain more than one key.

First generate a key pair. The defaults are fine, however you will have to enter at least your full name and email and optionally a comment . The comment is useful to create more than one key with the same name and email. Also you should use a "passphrase", not a simple password.
# gpg --gen-key # This can take a long time

The keys are stored in ~/.gnupg/ on Unix, on Wind ows they are typically stored in C:/Documents and Settings/%USERNAME%/Application Data/gnupg/.
~/.gnupg/pubring.gpg imported ~/.gnupg/secring.gpg # Contains your public keys and all others # Can contain more than one privat e key

Short reminder on most used options:


y y y y y

-e encrypt data -d decrypt data -r NAME encrypt for recipient NAME (or 'Full Name' or 'email@domain') -a create ascii armored output of a key -o use as output file

The examples use 'Your Name' and 'Alice' as the keys are referred to by the email or full name or partial name. For example I can use 'Colin' or 'c@cb.vu' for my key [Colin Barschel (cb.vu) <c@cb.vu>]. En crypt fo r pe rso nal use o nly No need to export/import any key for this. You have both already.
# gpg -e -r 'Your Name' file # gpg -o file -d file.gpg # Encrypt with your public key # Decrypt. Use -o or it goes to stdout

En crypt - Decrypt with keys First you need to export your public key for someone else to use it. And you need to import the public say from Alice to encrypt a file for her. You can either handle the keys in simple ascii files or use a public key server. For example Alice export her public key and you import it, you can then encrypt a file for her. That is only Alice will be able to decrypt it.
# # # # gpg gpg gpg gpg -a -o alicekey.asc --export 'Alice' # Alice exported her key in ascii file. --send-keys --keyserver subkeys.pgp.net KEYID # Alice put her key on a server. --import alicekey.asc # You import her key into your pubring. --search-keys --keyserver subkeys.pgp.net 'Alice' # or get her key from a server. # Encrypt the file for Alice. # Decrypt a file encrypted by Alice for

Once the keys are imported it is very easy to encr ypt or decrypt a file:
# gpg -e -r 'Alice' file # gpg -d file.gpg -o file you.

Key administration
# gpg --list-keys The KEYID follows the '/' e.g. for: pub # gpg --gen-revoke 'Your Name' # gpg --list-secret-keys # gpg --delete-keys NAME # gpg --delete-secret-key NAME # gpg --fingerprint KEYID # gpg --edit-key KEYID # list public keys and see the KEYIDS 1024D/D12B77CE the KEYID is D12B77CE # generate revocation certificate # list pr ivate keys # delete a public key from local key ring # delete a secret key from local key ring # Show the fingerprint of the key # Edit key (e.g sign or add/del email)

ENCRYPT PARTITIONS
Linux with LUKS | Linux dm-crypt only | FreeBSD GELI | FBSD pwd only There are (many) other alternative methods to encrypt disks, I only show here the me thods I know and use. Keep in mind that the security is only good as long the OS has not been tempered with. An intruder could easily record the password from the keyboard events. Furthermore the data is freely accessible when the partition is attached and will not prevent an intruder to have access to it in this state.

L i nu x
Those instructions use the Linux dm-crypt (device-mapper) facility available on the 2.6 kernel. In this example, lets encrypt the partition /dev/sdc1 , it could be however any othe r partition or disk, or USB or a file based partition created with losetup . In this case we would use /dev/loop0 . See file image partition. The device mapper uses labels to identify a partition. We use sdc1 in this example, but it could be any string. dm- crypt with LUKS

LUKS with dm-crypt has better encryption and makes it possible to have multiple passphrase for the same partition or to change the password easily. To test if LUKS is available, simply type # cryptsetup --help, if nothing about LUKS shows up, use the instr uctions below Without LUKS. First create a partition if necessary: fdisk /dev/sdc . Cre ate encrypted partition
# # # # # # # dd if=/dev/urandom of=/dev/sdc1 cryptsetup -y luksFormat /dev/sdc1 cryptsetup luksOpen /dev/sdc1 sdc1 mkfs.ext3 /dev/mapper/sdc1 mount -t ext3 /dev/mapper/sdc1 /mnt umount /mnt cryptsetup luksClose sdc1 # Optional. For paranoids only (takes days # This destroys any data on sdc1 # create ext3 file system # Detach the encrypted partition )

Attach
# cryptsetup luksOpen /dev/sdc1 sdc1 # mount -t ext3 /dev/mapper/sdc1 /mnt

De tach
# umount /mnt # cryptsetup luksClose sdc1

dm- crypt without LUKS


# # # # # # cryptsetup -y create sdc1 /dev/sdc1 dmsetup ls mkfs.ext3 /dev/mapper/sdc1 mount -t ext3 /dev/mapper/sdc1 /mnt umount /mn t/ cryptsetup remove sdc1 # or any other partition like /dev/loop0 # check it, will display: sdc1 (254, 0) # This is done only the first time! # Detach the encrypted partition

Do exactly the same (without the mkfs part!) to re -attach the partition. If the password is not correct, the mount command will fail. In this case simply remove the map sdc1 ( cryptsetup remove sdc1 ) and create it again.

F r e e BSD
The two popular FreeBSD disk encryption modules are gbde and geli. I now use geli because it is faster and also uses the crypto device for hardware acceleration. See The FreeBSD handbook Chapter 18.6http://www.freebsd.org/handbook/disks-encrypting.html for all the details. The geli module must be loaded or compiled into the kernel:
options GEOM_ELI device crypto # echo 'geom_eli_load="YES"' >> /boot/loader.conf # or as module: # or do: kldload geom_eli

Use passwo rd and key I use those settings for a typical disk encryption, it uses a passphrase AND a key to encrypt the master key. That is you need both the password and the generated key /root/ad1.key to attach the partition. The master key is stored inside the partition and is not visible. See below for typical USB or file based image. Cre ate encrypted partition
# # # # # # dd if=/dev/random of=/root/ad1.key bs=64 count=1 geli init -s 4096 -K /root/ad1.key /dev/ad1 geli attach -k /root/ad1.key /dev/ad1 dd if=/dev/random of=/dev/ad1.eli bs=1m newfs /dev/ad1.eli mount /dev/ad1.eli /mnt # this key encrypts the mater key # -s 8192 is also OK for di sks # DO make a backup of /root/ad1.key # Optional and takes a long time # Create file system

Attach
# geli attach -k /root/ad1.key /dev/ad1 # fsck -ny -t ffs /dev/ad1.eli # mount /dev/ad1.eli /mnt # In doubt check the file system

De tach The detach procedure is done automatically on shutdown.


# umount /mnt # geli detach /dev/ad1.eli

/e tc/fstab The encrypted partition can be configured to be mounted with /etc/fstab. The password will be prompted when booting. The following settings are required for this example:
# grep geli /etc/rc.conf geli_devices="ad1" geli_ad1_flags=" -k /root/ad1.key" # grep geli /etc/fstab /dev/ad1.eli /home/private

ufs

rw

Use passwo rd o nly It is more convenient to encrypt a USB stick or file based image with a passphrase only and no key. In this case it is not necessary to carry the additional key file around. The procedure is very much the same as above, simply without the key file. Let's encrypt a file based image /cryptedfile of 1 GB.
# # # # # # # # dd if=/dev/zero of=/cryptedfile bs=1M count=1000 mdconfig -at vnode -f /cryptedfile geli init /dev/md0 geli attach /dev/md0 newfs -U -m 0 /dev/md0.eli mount /dev/md0.eli /mnt umount /dev/md0.eli geli detach md0.eli # 1 GB file # encrypts with password only

It is now possible to mount this image on an other system with the password only.
# mdconfig -at vnode -f /cryptedfile # geli attach /dev/md0 # mount /dev/md0.eli /mnt

S S L C E R T I F I C AT E S
So called SSL/TLS certificates are cryptographic public key certificate s and are composed of a public and a private key. The certificates are used to authenticate the endpoints and encrypt the data. They are used for example on a web server (https) or mail server (imaps).

Pr oc ed ur e
y y

y y

We need a certificate authority to sign our certificate. This step is usually provided by a vendor like Thawte, Verisign, etc., however we can also create our own. Create a certificate signing request. This request is like an unsigned certificate (the public part) and already contains all necessary information. The certificate request is normally sent to the authority vendor for signing. This step also creates the private key on the local machine. Sign the certificate with the certificate authority. If necessary join the certificate and the key in a single file to be used by the application (web server, mail server etc.).

Con fi g ur e O p e nS SL

We use /usr/local/certs as directory for this example check or edit /etc/ssl/openssl.cnf accordingly to your settings so you know where the files will be created. Here are the relevant part of openssl.cnf:
[ CA_default ] dir certs crl_dir database # # # # # = = = = /usr/local/certs/CA $dir/certs $dir/crl $dir/index.txt # # # # Where everything is kept Where the issued certs are kept Where the issued crl are kept database index file.

Make sure the directories exist or create them


mkdir -p /usr/local/certs/CA cd /usr/local/certs/CA mkdir ce rts crl newcerts private echo "01" > serial touch index.txt

# Only if serial does not exist

If you intend to get a signed certificate from a vendor, you only need a certificate signing request (CSR). This CSR will then be signed by the vendor for a limited time (e.g. 1 year).

Cr e a t e a c er t i fi c a t e au t h or i t y
If you do not have a certificate authority from a vendor, you'll have to create your own. This step is not necessary if one intend to use a vendor to sign the request. To make a certificate authority (CA):
# openssl req -new -x509 -days 730 -config /etc/s sl/openssl.cnf \ -keyout CA/private/cakey.pem -out CA/cacert.pem

Cr e a t e a c er t i fi c a t e s i g ni n g r e qu e s t
To make a new certificate (for mail server or web server for example), first create a request certificate with its private key. If your application do not support encrypted private key (for example UW-IMAP does not), then disable encryption with -nodes .
# openssl req -new -keyout newkey.pem -out newreq.pem \ -config /etc/ssl/openssl.cnf # openssl req -nodes -new -keyout newkey.pem -out newreq.pem \ -config /etc/ssl/openssl.cnf # No encryption for the key Keep this created CSR ( newreq.pem ) as it can be signed again at the next renewal, the

signature onlt will limit the validity of the certificate. This process also created the private key newkey.pem .

Si gn th e cer t ifi c a t e
The certificate request has to be signed by the CA to be valid, this ste p is usually done by the vendor. Note: replace "servername" with the name of your server in the next commands .
# cat newreq.pem newkey.pem > new.pem # openssl ca -policy policy_anything -out servernamecert.pem \ -config /etc/ssl/openssl.cnf -infiles new.p em # mv newkey.pem servernamekey.pem

Now servernamekey.pem is the private key and servernamecert.pem is the server certificate.

Cr e a t e u ni t e d c er t i fi c a t e
The IMAP server wants to have both private key and server certificate in the same file. And in general, this is also easier to handle, but the file has to be kept securely!. Apache also can deal with it well. Create a file servername.pem containing both th e certificate and key.
y y

Open the private key (servernamekey.pem) with a text editor and copy the private key into the "servername.pem" file. Do the same with the server certificate (servernamecert.pem).

The final servername.pem file should look like this:

-----BEGIN RSA PRIVATE KEY ----MIICXQIBAAKBgQDutWy+o/XZ/[...]qK5LqQgT3c9dU6fcR+WuSs6aejdEDDqBRQ -----END RSA PRIVATE KEY ---------BEGIN CERTIFICATE ----MIIERzCCA7CgAwIBAgIBBDANB[...]iG9w0BAQQFADCBxTELMAkGA1UEBhMCREUx -----END CERTIFICATE -----

What we have now in the directory /usr/local/certs/:


y y y y y

CA/private/cakey.pem (CA server private key) CA/cacert.pem (CA server public key) certs/servernamekey.pem (server private key) certs/servernamecert.pem (server signed certificate) certs/servername.pem (server certificate with private key)

Keep the private key secure!

Vi e w c er ti fi c at e i n for m a t i on
To view the certificate information simply do:
# openssl x509 -text -in servernamecert.pem # openssl req -noout -text -in server.csr # openssl s_client -connect cb.vu:443 # View the certificate info # View the request info # Check a web server certificate

CVS
Server setup | CVS test | SSH tunneling | CVS usage

Ser v er s e tu p
In itiate the CVS Decide where the main repository will rest and create a root cvs. For example /usr/local/cvs (as root):
# mkdir -p /usr/local/cvs # setenv CVSROOT /usr/local/cvs # cvs init # cd /root # cvs checkout CVSROOT # cd CVSROOT edit config ( fine as it is) # cvs commit config cat >> writers colin ^D # cvs add writers # cvs edit checkoutlist # cat >> checkoutlist writers ^D # cvs commit # Set CVSROOT to the new location (local) # Creates all internal CVS config files # Checkout the config files to modify them

# Create a writers file (optionally

also readers)

# Use [Control][D] to quit the edit # Add the file writers into the repository

# Use [Control][D] to quit the edit # Commit all the configuration changes

Add a readers file if you want to differentiate read and write permissions Note: Do not (ever) edit files directly into the main cvs, b ut rather checkout the file, modify it and check it in. We did this with the file writers to define the write access. There are three popular ways to access the CVS at this point. The first two don't need any further configuration. See the examples on CVSROOT below for how to use them:
y

Direct local access to the file system. The user(s) need sufficient file permission to access the CS directly and there is no further authentication in addition to the OS login. However this is only useful if the repository is local.

Remote access with ssh with the ext protocol. Any use with an ssh shell account and read/write permissions on the CVS server can access the CVS directly with ext over ssh without any additional tunnel. There is no server process running on the CVS for this to work. The ssh login does the authentication. Remote access with pserver (default port: 2401/tcp). This is the preferred use for larger user base as the users are authenticated b y the CVS pserver with a dedicated password database, there is therefore no need for local users accounts. This setup is explained below.

Ne two rk setu p with inetd The CVS can be run locally only if a network access is not needed. For a remote access, the daemon inetd can start the pserver with the following line in /etc/inetd.conf (/etc/xinetd.d/cvs on SuSE):
cvspserver stream tcp nowait cvs --allow-root=/usr/local/cvs pserver /usr/bin/cvs cvs \

It is a good idea to block the cvs port from the Interne t with the firewall and use an ssh tunnel to access the repository remotely. Se parate au thentication It is possible to have cvs users which are not part of the OS (no local users). This is actually probably wanted too from the security point of view. Simp ly add a file named passwd (in the CVSROOT directory) containing the users login and password in the crypt format. This is can be done with the apache htpasswd tool. Note: This passwd file is the only file which has to be edited directly in the CVSROOT directory. Also it won't be checked out. More info with htpasswd --help
# htpasswd -cb passwd user1 password1 # -c creates the file # htpasswd -b passwd user2 password2 Now add :cvs at the end of each line to tell the cvs server to change the user to cvs (or

whatever your cvs server is running under). It looks like this:


# cat passwd user1:xsFjhU22u8Fuo:cvs user2:vnefJOsnnvToM:cvs

Tes t it
Test the login as normal user (for example here me)
# cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs login Logging in to :pserver:colin@192.168.50.254:2401/usr/local/cvs CVS password:

CVS ROOT variable This is an environment variable used to specify the location of the repository we're doing operations on. For local use, it can be just set to the directory of the repository. For use over the network, the transport protocol must be specified. Set the CVSR OOT variable with setenv CVSROOT string on a csh, tcsh shell, or with export CVSROOT=string on a sh, bash shell.
# setenv CVSROOT For example: # setenv CVSROOT # setenv CVSROOT # setenv CVSROOT # setenv CVS_RSH # setenv CVSROOT :pserver:<username>@<host>:/cvsdirectory /usr/local/cvs :local:/usr/local/cvs :ext:user@cvsserver:/usr/local/cvs ssh :pserver:user@cvsserver.254:/usr/local/cvs # # # # # Used lo cally only Same as above Direct access with SSH for the ext acce ss network with pserver

When the login succeeded one can import a new project into the repository: cd into your project root directory
cvs import <module name> <vendor tag> <initial tag>

cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs import MyProject MyCompany START

Where MyProject is the name of the new project in the repository (used later to checkout). Cvs will import the current directory content into the new project. To checkout:
# cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs checkout MyProject or # setenv CVSROOT :pserver:colin@192.168.50.254:/usr/local/cvs # cvs checkout MyProject

SSH t u nn e li n g for CVS


We need 2 shells for this. On the first shell we connect to the cvs serv er with ssh and portforward the cvs connection. On the second shell we use the cvs normally as if it where running locally. on shell 1:
# ssh -L2401:localhost:2401 colin@cvs_server Or: # ssh -L2401:cvs_server:2401 colin@gateway # Connect directly to the CVS server. # Use a gateway to reach the CVS

on shell 2:

# setenv CVSROOT :pserver:colin@localhost:/usr/local/cvs # cvs login Logging in to :pserver:colin@localhost:2401/usr/local/cvs CVS password: # cvs checkout MyProject/src

CVS c om m a n d s a n d us a g e
Im po rt The import command is used to add a whole directory, it must be run from within the directory to be imported. Say the directory /devel/ contains all files and subdirectories to be imported. The directory name on the CVS (the module) will be called "myapp".
# cvs import [options] directory -name vendor -tag release -tag # cd /devel # Must be inside the project to import it # cvs import myapp Company R1_0 # Release tag can be anything in one word

After a while a new directory "/devel/tools/" was added and it has to be imported too.
# cd /devel/tools # cvs import myapp/tools Company R1_0

Checkout update add commit


# # # # # # # # cvs cvs cvs cvs cvs cvs cvs cvs co myapp/tools co -r R1_1 myapp -q -d update -P update -A add newfile add -kb newfile commit file1 file2 commit -m "message" # Will only checkout the directory tools # Che ckout myapp at release R1_1 (is sticky) # A typical CVS update # Reset any sticky tag (or date, option) # Add a new file # Add a new binary file # Commit the two files only # Commit all changes done with a message

Create a patch It is best to create and apply a patch from the working devel opment directory related to the project, or from within the source directory.
# cd /devel/project # diff -Naur olddir newdir > patchfile # Create a patch from a directory or a file # diff -Naur oldfile newfile > patchfile

Appl y a patch

Sometimes it is necessary to strip a directory level from the patch, depending how it was created. In case of difficulties, simply look at the first lines of the patch and try -p0, -p1 or p2.
# # # # cd /devel/project patch --dry-run -p0 < patchfile patch -p0 < patchfile patch -p1 < patchfile # Tes t the path without applying it # strip off the 1st level from the path

SVN
Server setup | SVN+SSH | SVN over http | SVN usage Subversion (SVN)http://subversion.tigris.org/ is a version control system designed to be the successor of CVS (Concurrent Versions System). The concept is similar to CVS, but many shortcomings where improved. See also the SVN bookhttp://svnbook.red-bean.com/en/1.4/.

Ser v er s e tu p
The initiation of the repository is fairly simple (here for example /home/svn/ must exist):
# svnadmin create --fs-type fsfs /home/svn/project1

Now the access to the repository is made possible with:


y y y file:// Direct file system access with the svn client with. This requires local permissions on the file system. svn:// or svn+ssh:// Remote access with the svnserve server (also over SSH). This requires local permissions on the file system (default port: 2690/tcp). http:// Remote access with webdav using apache. No local users are necessary for this method.

Using the local file system, it is now possible to import and then check out an existing project. Unlike with CVS it is not necessary to cd into the project directory, simply give the full path:
# svn import /project1/ file:///home/svn/project1/trunk # svn checkout file:///home/svn/project1 -m 'Initial import'

The new directory "trunk" is only a convention, this is not required. Remo te access with ssh No special setup is required to access the repository via ssh, simply replace file:// with
svn+ssh/hostna me. For example: # svn checkout svn+ssh://hostname/home/svn/project1

As with the local file access, every user needs an ssh access to the server (with a local account) and also read/write access. This method might be suitable for a small group. All users could belong to a subversion group which owns the repository, for example:
# # # # groupadd groupmod chown -R chmod -R subversion -A user1 subversion root:subversion /home/svn 770 /home/svn

Remo te access with h ttp (apache ) Remote access over http (https) is the only good solution for a larger user group. This method uses the apache authentication, not the local accounts. This is a typical but small apache configuration:
LoadModule dav_module LoadModule dav_svn_module LoadModule authz_svn_module <Location /svn> modules/mod_dav.so modules /mod_dav_svn.so modules/mod_authz_svn.so # Only for access control

DAV svn # any "/svn/foo" URL will map to a repository /home/svn/foo SVNParentPath /home/svn AuthType Basic AuthName "Subversion repository" AuthzSVNAccessFile /etc/apache2/svn.acl AuthUserFile /etc/apache2/svn -passwd Require valid -user </Location>

The apache server needs full access to the repository:


# chown -R www:www /home/svn

Create a user with htpasswd2:


# htpasswd -c /etc/svn -passwd user1 # -c creates the file

Acce ss control svn.acl e xample


# Default it read access. "* =" would be default no access [/] * = r [groups] project1-developers = joe, jack, jane # Give write access to the developers [project1:] @project1 -developers = rw

S VN c om m a n d s a n d us a g e
See also the Subversion Quick Reference Cardhttp://www.cs.put.poznan.pl/csobaniec/Papers/svnrefcard.pdf. Tortoise SVNhttp://tortoisesvn.tigris.org is a nice Windows interface. Im po rt A new project, that is a directory with some files, is imported into the repository with the import command. Import is also used to add a directory with its content to an existing project.
# svn help import # Get help for any command # Add a new directory (with content) into the src dir on project1 # svn import /project1/newdir http://host.url/svn/project1/trunk/src -m 'add newdir'

Typical S VN comman ds
# svn # # svn # svn # # # # # # svn svn svn svn svn svn co http://host.url/svn/project1/trunk # Checkout the most recent version Tags and branches are created by copying mkdir http://host.url/svn/project1/tags/ # Create the tags directory copy -m "Tag rc1 rel." http://host.url/svn/project1/trunk \ http://host.url/svn/project1/tags/1.0rc1 status [ --verbose] # Check files status into working dir add src/file.h src/file.cpp # Add two files commit -m 'Added new class file' # Commit the changes with a message ls http://host.url/svn/project1/tags/ # List all tags move foo.c bar.c # Move (rename) files delete some_old_file # Delete files

USEFUL COMMANDS
less | vi | mail | tar | dd | screen | find | Miscellaneous

le s s
The less command displays a text document on the console. It is present on most installation.

# less unixtoolbox.xhtml

Some important commands are (^N stands for [control] -[N]):


y y y y y y y y y

hH good help on display f ^F ^V SPACE Forward one window (or N lines). b ^B ESC-v Backward one window (or N lines). F Forward forever; like "tail -f". /pattern Search forward for (N-th) matching line. ?pattern Search backward for (N-th) matching line. n Repeat previous search (for N-th occurrence). N Repeat previous search in reverse direction. q quit

vi
Vi is present on ANY Linux/Unix installation (not gentoo?) and it is therefore useful to know some basic commands. There are two modes: command mode and insertion mode. The commands mode is accessed with [ESC], the insertion mode with i. Use : help if you are lost. The editors nano and pico are usually available too and are easier (IMHO) to use. Quit
y y y

:w newfilename save the file to newfilename :wq or :x save and quit :q! quit without saving

Search and move


y y y y y y y y y y

/string Search forward for string ?string Search back for string n Search for next instance of string N Search for previous instance of string { Move a paragraph back } Move a paragraph forward 1G Move to the first line of the file nG Move to the n th line of the file G Move to the last line of the file :%s/OLD/NEW/g Search and replace every occurrence

Delete copy paste te xt


y y y y y y y

dd (dw) Cut current line (word) D Cut to the end of the line x Delete (cut) character yy (yw) Copy line (word) after cursor P Paste after cursor u Undo last modification U Undo all changes to current line

m a il
The mail command is a basic application to read and send email, it is usually installed. To send an email simply type "mail user@domain". The first line is the subject, then the mail content. Terminate and send the email with a single dot (.) in a new line. Exampl e:
# mail c@cb.vu Subject: Your text is full of typos

"For a moment, nothing happened. Then, after a second or so, nothing continued to happen." . EOT #

This is also working with a pipe:


# echo "This is the mail body" | mail c@cb.vu

This is also a simple way to test the mail server.

t ar
The command tar (tape archive) creates and extracts archives of file and directories. The archive .tar is uncompressed, a compressed archive has the extension .tgz or .tar.gz (zip) or .tbz (bzip2). Do not use absolute path when creating an archive, you probably want to unpack it somewhere else. Some typical commands are: Create
# # # # cd / tar -cf home.tar home/ tar -czf home.tgz home/ tar -cjf home.tbz home/ # archive the whole /home directory (c for create) # same with zip compression # same with bzip2 compression

Only include one (or two) directories from a tree, but keep the relative structure. For example archive /usr/local/etc and /usr/local/www and the first directory in the archive shoul d be local/.
# tar -C /usr -czf local.tgz local/etc local/www # tar -C /usr -xzf local.tgz # To untar the local dir into /usr # cd /usr; tar -xzf local.tgz # Is the same as above

Extract
# tar -tzf home.tgz # tar -xf home.tar # tar -xzf home.tgz compression) # look inside the archive witho ut extracting (list) # extract the archive here (x for extract) # same with zip compression ( -xjf for bzip2

# remove leading path gallery2 and extr act into gallery # tar --strip-components 1 -zxvf gallery2.tgz -C gallery/ # tar -xjf home.tbz home/colin/file.txt # Restore a single file

Mo re advance d
# # # # # tar tar tar tar tar c dir/ | gzip cvf - `find . -cf - -C /etc -cf - -C /etc -czf home.tgz | ssh user@remote 'dd of=dir.tgz' -print` > backup.tar . | tar xpf - -C /backup/etc . | ssh user@remote tar xpf - -C --exclude '*.o' --exclude 'tmp/' # arch dir/ and store remotely. # arch the current directory. # Copy directories /backup/etc # Remote copy. home/

dd
The program dd (disk dump or destroy disk or see the meaning of dd) is used to copy partitions and disks and for other copy tricks. Typical usage:
# dd if=< source> of=<target> bs=<byte size> conv=<conversion>

Important conv options:


y y y

notrunc do not truncate the output file, all zeros will be written as zeros. noerror continue after read errors (e.g. bad blocks) sync pad every input block with Nulls to ibs-size

The default byte size is 512 (one block). The MBR, where the partition table is located, is on the first block, the first 63 blocks of a disk are empty. Larger byte sizes are faster to copy but require also more memory. Backup and resto re
# # # # # # # # dd if=/dev/hda of=/dev/hdc bs=16065b # Copy disk to disk (same size) dd if=/dev/sda7 of=/home/root.img bs=4096 conv=notrunc,noerror # Backup / dd if=/home/root.img of=/dev/sda7 bs=4096 conv=notrunc,noerror # Restore / dd bs=1 M if=/dev/ad4s3e | gzip -c > ad4s3e.gz # Zip the backup gunzip -dc ad4s3e.gz | dd of=/dev/ad0s3e bs=1M # Restore the zip dd bs=1M if=/dev/ad4s3e | gzip | ssh eedcoba@fry 'dd of=ad4s3e.gz' # also remote gunzip -dc ad4s3e.gz | ssh eedcoba@host 'dd of=/dev/ad0s3e bs=1M' dd if=/dev/ad0 of=/dev/ad2 skip=1 seek=1 bs=4k conv=noerror # Skip MBR # This is necessary if the destination (ad2) is smaller.

Re cove r The command dd will read every single block of the partition. In case of problems it is better to use the option conv=sync,noerror so dd will skip the bad block and write zeros at the destination. Accordingly it is important to set the block size equal or smaller than the disk block size. A 1k size seems safe, set it with bs=1k. If a disk has bad sectors and the data should be recovered from a partition, create an image file with dd, mount the image and copy the content to a new disk. With the option noerror , dd will skip the bad sectors and write zeros instead, thus only the data contained in the bad sectors will be lost.
# dd if=/dev/hda of=/dev/null bs=1m # Check for bad blocks # dd bs=1k if=/dev/hda1 conv=sync,noerror,notrunc | gzip | ssh \ # Send to remote root@fry 'dd of=hda1.gz bs=1k' # dd bs=1k if=/dev/hda1 conv=sync,noerror,notrunc of=hda1.img # Store into an image # mount -o loop /hda1.img /mnt # Mount the image # rsync -ax /mnt/ /newdisk/ # Copy on a new disk # dd if=/dev/hda of=/dev/hda # Refresh the magnetic state # The above is useful to refresh a disk. It is perfectly safe, but must be unmounted.

Delete
# # # # dd if=/dev/zero o f=/dev/hdc dd if=/dev/urandom of=/dev/hdc kill -USR1 PID kill -INFO PID # Delete full disk # Delete full disk better # View dd progress (Linux) # View dd progress (FreeBSD)

MBR tricks The MBR contains the boot loader and the partition table and is 512 bytes small. The first 446 are for the boot loader, the bytes 446 to 512 are for the partition table.
# dd if=/dev/sda of=/mbr_sda.bak bs=512 count=1 # Backup the full MBR # dd if=/dev/zero of=/dev/sda bs=512 count=1 # Delete MBR and partition table # dd if=/mbr_sda.bak of=/dev/sda bs=512 count=1 # Restore the full MBR # dd if=/mbr_sda.bak of=/dev/sda bs=446 count=1 # Restore only the boot loader # dd if=/mbr_sda.bak of=/dev/sda bs=1 count=64 skip=446 seek=446 # Restore partition table

s cr e en
Screen (a must have) has two main functionalities:
y y

Run multiple terminal session within a single terminal. A started program is decoupled from the real terminal and can thus run in the background. The real terminal can be closed and reattached later.

Sho rt start e xample start screen with:


# screen

Within the screen session we can start a long lasting program (like top).
# top

Now detach with Ctrl-a Ctrl-d. Reattach the terminal with:


# screen -R -D

In detail this means: If a session is running, then reattach. If necessary detach and logout remotely first. If it was not running create it and notify the user. Or:
# screen -x

Attach to a running screen in a multi display mode. The console is thus share d among multiple users. Very useful for team work/debug! S creen comman ds (with in scree n ) All screen commands start with Ctrl-a.
y y y y y y y y

Ctrl-a ? help and summary of functions Ctrl-a c create an new window (terminal) Ctrl-a Ctrl-n and Ctrl-a Ctrl-p to switch to the next or previous window in the list, by number. Ctrl-a Ctrl-N where N is a number from 0 to 9, to switch to the corresponding window. Ctrl-a " to get a navigable list of running windows Ctrl-a a to clear a missed Ctrl-a Ctrl-a Ctrl-d to disconnect and leave the session running in the background Ctrl-a x lock the screen terminal with a password

The screen session is terminated when the program within the running terminal is closed and you logout from the terminal.

F in d
Some important options:
y y y y y y -x (on BSD) -xdev (on Linux) Stay on the same file system (dev in fstab). -exec cmd {} \; Execute the command and replace {} with the full path -iname Like -name but is case insensitive -ls Display information about the file (like ls -la) -size n n is +-n (k M G T P) -cmin n File's status was last changed n minutes ago.

# find . -type f ! -perm -444 # Find files not readable by all # find . -type d ! -perm -111 # Find dirs not accessible by all # find /home/user/ -cmin 10 -print # Files created or modified in the last 10 min. # find . -name '*.[ch]' | xargs grep -E 'expr' # Search 'expr' in this dir and below. # find / -name "*.core" | xargs rm # Find core dumps and delete t hem (also try core.*) # find / -name "*.core" -print -exec rm {} \; # Other syntax # Find images and create an archive, iname is not case sensitive. -r for append # find . \( -iname "*.png" -o -iname "*.jpg" \) -print -exec tar -rf images.tar {} \; # find . -type f -name "*.txt" ! -name README.txt -print # Exclude README.txt files # find /var/ -size +10M -exec ls -lh {} \; # Find large files > 10 MB # find /var/ -size +10M -ls # This is simpler # find . -size +10M -size -50M -print # find /usr/ports/ -name work -type d -print -exec rm -rf {} \; # Clean the ports # Find files with SUID; those file are vulnerable and must be kept secure # find / -type f -user root -perm -4000 -exec ls -l {} \;

Be careful with xarg or exec as it might or might not honor quotings and can return wrong results when files or directories contain spaces. In doubt use "-print0 | xargs -0" instead of "| xargs". The option -print0 must be the last in the find command. See this nice mini tutorial for findhttp://www.hccfl.edu/pollock/Unix/FindCmd.htm.
# find . -type f | xargs ls -l # Will not work with spaces in names # find . -type f -print0 | xargs -0 ls -l # Will work with spaces in names # find . -type f -exec ls -l '{}' \; # Or use quotes '{}' with -exec

M is c el l a n e ous
# # # # # # # # # # # # # # # # # # # # # # which command # Show full path name of command time command # See how long a command takes to execute time cat # Use time as stopwatch. Ctrl -c to stop set | grep $USER # List the current environment cal -3 # Display a three month calendar date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]] date 10022155 # Set date and time whatis grep # Display a short info on the command or word whereis java # Search path and standard directories for word setenv varname value # Set env. variable varname to value (csh/tcsh) export varname="value" # set env. variable varname to value (sh/ksh/bash) pwd # Print working directory mkdir -p /path/to/dir # no error if existin g, make parent dirs as needed mkdir -p project/{bin,src,obj,doc/{html,man,pdf},debug/some/more/dirs} rmdir /path/to/dir # Remove directory rm -rf /path/to/dir # Remove directory and its content (force) cp -la /dir1 /d ir2 # Archive and hard link files instead of copy cp -lpR /dir1 /dir2 # Same for FreeBSD cp unixtoolbox.xhtml{,.bak} # Short way to copy the file with a new extension mv /dir1 /dir2 # Rename a directory ls -1 # list one file per line history | tail -50 # Display the last 50 used commands Check file hashes with openssl. This is a nice alternative to the commands md5sum or sha1sum (FreeBSD uses md5 and sha1) which are not always installed. # openssl md5 file.tar.gz # Generate an md5 checksum from file # openssl sha1 file.tar.gz # Generate an sha1 checksum from file # openssl rmd160 file.tar.gz # Generate a RIPEMD -160 checksum from file

I N S T A L L S O F T W A RE
Usually the package manager uses the proxy variable for http/ftp requests. In .bashrc:
export http_proxy=http://proxy_server:3128 export ftp_proxy=http://proxy_server:3128

L is t in s t a ll e d p a ck a g es
# # # # # rpm -qa dpkg -l pkg_info pkg_info -W smbd pkginfo # List installed packages (RH, SuSE, RPM based) # Debian, Ubuntu # FreeBSD list all installed packages # FreeBSD show which package s mbd belongs to # Solaris

A d d /r e m ov e s oft w ar e
Front ends: yast2/yast for SuSE, redhat-config-packages for Red Hat.
# rpm -i pkgname.rpm # rpm -e pkgname # install the package (RH, SuSE, RPM based) # Remove package

Debian
# apt-get update # First update the package lists

# apt-get install emacs # dpkg --remove emacs # dpkg -S file

# Install the package emacs # Remove the package emacs # find what package a file belongs to

Gentoo Gentoo uses emerge as the heart of its "Portage" package management system.
# # # # emerge --sync emerge -u packagename emerge -C packagename revdep-rebuild # # # # First sync the local portage tree Inst all or upgrade a package Remove the package Repair dependencies

Solaris The <cdrom> path is usually /cdrom/cdrom0 .


# pkgadd -d <cdrom>/Solaris_9/Product SUNWgtar # pkgadd -d SUNWgtar # Add downloaded package (bunzip2 first) # pkgrm SUNWgtar # Remove the package

FreeBS D
# Fetch and install rsync. # Delete the rsync package Set where the packages are fetched from with the PACKAGESITE variable. For example: # export PACKAGESITE=ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages/Latest/ # or ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages -6-stable/Latest/ # pkg_add -r rsync # pkg_delete /var/db/pkg/rsync -xx

FreeBS D ports http:// www. freebs d.o rg/handbook/ po rts. html The port tree /usr/ports/ is a collection of software ready to compile and install (see man ports). The ports are updated with the program portsnap .
# # # # # # portsnap fetch extract portsnap fetch update cd /usr/ports/net/rsync/ make install distclean make package pkgdb -F # # # # # # Create the tree when running the first time Update the port tree Select the package to install Install and cleanup (also see man ports) Make a binary package of this port Fix the package registry database

L i br ar y p at h
Due to complex dependencies and runtime linking, programs are d ifficult to copy to an other system or distribution. However for small programs with little dependencies, the missing libraries can be copied over. The runtime libraries (and the missing one) are checked with ldd and managed with ldconfig .
# # # # ldd /usr/bin/ rsync ldconfig -n /path/to/libs/ ldconfig -m /path/to/libs/ LD_LIBRARY_PATH # # # # List all needed runtime libraries Add a path to the shared libraries directories FreeBSD The variable set the link library path

CONVERT MEDIA
Sometimes one simply need to convert a video, audio file or document to another format.

Te x t e n c odi n g
Text encoding can get totally wrong, specially when the language requires special characters like . The command iconv can convert from one encoding to an other.
# iconv -f <from_encoding> -t <to_encoding> <input_file> # iconv -f ISO8859-1 -t UTF-8 -o file.input > file_utf8

# iconv -l

# List known coded character sets

Without the -f option, iconv will use the local char-set, which is usually fine if the document displays well.

U ni x - D O S n e w l in e s
Convert DOS (CR/LF) to Unix (LF) newlines and back within a Unix shell. See also dos2unix and unix2dos if you have them.
# sed 's/.$//' dosfile.txt > unixfile.txt # awk '{sub(/ \r$/,"");print}' dosfile.txt > unixfile.txt # awk '{sub(/$/," \r");print}' unixfile.txt > dosfile.txt # DOS to UNIX # DOS to UNIX # UNIX to DOS

Convert Unix to DOS newlines within a Windows environment. Use sed or awk from mingw or cygwin.
# sed -n p unixfile.txt > dosfile.txt # awk 1 unixfile.txt > dosfile.txt # UNIX to DOS (with a cygwin shell)

PD F t o J p e g a n d c on c at e n a t e PD F fi l es
Convert a PDF document with gs (GhostScript) to jpeg (or png) images for each page. Also much shorter with convert and mogrify (from ImageMagick or GraphicsMagick).
# gs -dBATCH -dNOPAUSE -sDEVICE=jpeg -r150 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 \ -dMaxStripSize=8192 -sOutputFile=unixtoolbox_%d.jpg unixtoolbox.pdf # convert unixtoolbox.pdf unixtoolbox -%03d.png # convert *.jpeg images.pdf # Create a simple PDF with all pictures # convert image000* -resample 120x120 -compress JPEG -quality 80 images.pdf # mogrify -format png *.ppm # convert all ppm images to p ng format

Ghostscript can also concatenate multiple pdf files into a single one. This only works well if the PDF files are "well behaved".
# gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=all.pdf \ file1.pdf file2.pdf ... # On Windows use '#' instead of '='

Conv er t v i d e o
Compress the Canon digicam video with an mpeg4 codec and repair the crappy sound.
# mencoder -o videoout.avi -oac mp3lame -ovc lavc -srate 11025 \ -channels 1 -af-adv force=1 -lameopts preset=medium -lavcopts \ vcodec=msmpeg4v2:vbitrate=600 -mc 0 vidoein.AVI

See sox for sound processing.

Copy a n a u di o c d
The program cdparanoia http://xiph.org/paranoia/ can save the audio tracks (FreeBSD port in audio/cdparanoia/), oggenc can encode in Ogg Vorbis format, lame converts to mp3.
# # # # cdparanoia -B # Copy the tracks to wav files in current dir lame -b 256 in.wav out.mp3 # Encode in mp3 256 kb/s for i in *.wav; do lame -b 256 $i `basename $i .wav`.mp3; done oggenc in.wav -b 256 out.ogg # Encode in Ogg Vorbis 256 kb/s

PRINTING
Pr i nt w i t h l pr
# # # # # # # lpr unixtoolbox.ps # Print on default printer export PRINTER=hp4600 # Change the default printer lpr -Php4500 #2 unixtoolbox.ps # Use printer hp4500 and print 2 copies lpr -o Duplex=DuplexNoTumble ... # Print duplex along the long side lpr -o PageSize=A4,Duplex=Duple xNoTumble ... lpq # Check the queue on default printer lpq -l -Php4500 # Queue on printer hp4500 with verbose

# # # #

Some devices are not postscript and will print garbage when fed with a pdf file. This might be solved with:
# gs -dSAFER -dNOPAUSE -sDEVICE=deskjet -sOutputFile= \|lpr file.pdf Print to a PDF file even if the application does not support it. Use gs on the print command instead of lpr. # gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=/path/file.pdf

lprm lprm -Php4500 3186 lpc status lpc status hp4500

# Remove all users jobs on default printer # Remove job 3186. Find job nbr with lpq # List all available printers # Check if printer is online and queue length

DATABASES
P os t gr e SQ L
Chan ge roo t o r a use rname password
# psql -d template1 -U pgsql > alter user pgsql with password 'pgsql_password'; # Use username instead of "pgsql"

Create use r an d database The commands createuser , dropuser , createdb and dropdb are convenient shortcuts equivalent to the SQL commands. The new user is bob with database bobdb ; use as root with pgsql the database super user:
# # # # createuser -U pgsql -P bob createdb -U pgsql -O bob bobdb dropdb bobdb dropuser bob # -P will ask for password # new bobdb is owned by bob # Delete database bobdb # De lete user bob

The general database authentication mechanism is configured in pg_hba.conf Gran t remo te access The file $PGSQL_DATA_D/postgresql.conf specifies the address to bind to. Typically listen_addresses = '*' for Postgres 8.x. The file $PGSQL_DATA_D /pg_hba.conf defines the access control. Examples: # TYPE DATABASE USER IP -ADDRESS IP -MASK METHOD host bobdb bob 212.117.81.42 255.255.255.255 password host all all 0.0.0.0/0 password Backup and resto re The backups and restore are done with the user pgsql or postgres. Backup and restore a single database:
# pg_dump --clean dbname > dbname_sql.dump # psql dbname < dbname_sql.dump

Backup and restore all databases (including users):


# pg_dumpall --clean > full.dump # psql -f full.dump postgres

In this case the restore is started with the database postgres which is better when reloading an empty cluster.

M y SQ L
Chan ge mys ql roo t o r use rname passwo rd Me thod 1
# /etc/init.d/mysql stop

or # killall mysqld # mysqld --skip-grant-tables # mysqladmin -u root password 'newpasswd' # /etc/init.d/mysql start

Me thod 2
# mysql -u root mysql mysql> UPDATE USER SET PASSWORD=PASSWORD("newpassword") where user='root'; mysql> FLUSH PRIVILEGES; # Use username instead of "root" mysql> quit

Create use r an d database (see MySQL doc http:// dev.m ysql. com/do c/ re fman /5.1/en/addin g-use rs.h tml )
# mysql -u root mysql mysql> CREATE USER 'bob'@'localhost' IDENTIFIED BY 'pwd'; # create only a user mysql> CREATE DATABASE bobdb; mysql> GRANT ALL ON *.* TO 'bob'@'%' IDENTIFIED BY 'pwd'; # Use loc alhost instead of % # to restrict the network access mysql> DROP DATABASE bobdb; # Delete database mysql> DROP USER bob; # Delete user mysql> DELETE FROM mysql.user WHERE user='bob and host='hostname'; # Alt. command mysql> FLUSH PRIVILEGES;

Gran t remo te access Remote access is typically permitted for a database, and not all databases. The file
/etc/my.cnf contains the IP address to bind to. Typically comm ent the line bind-address =

out.
# mysql -u root mysql mysql> GRANT ALL ON bobdb.* TO bob@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD'; mysql> REVOKE GRANT OPTION ON foo.* FROM bar@'xxx.xxx.xxx.xxx'; mysql> FLUSH PRIVILEGES; # Use 'hostname' or also '%' for full access

Backup and resto re Backup and restore a single database:


# mysqldump -u root -psecret --add-drop-database dbname > dbname_sql.dump # mysql -u root -psecret -D dbname < dbname_sql.dump

Backup and restore all databases :


# mysqldump -u root -psecret --add-drop-database --all-databases > full.dump # mysql -u root -psecret < full.dump

Here is "secret" the mysql root password, there is no space after -p. When the -p option is used alone (w/o password), the password is asked at the command prompt.

SQ L it e
SQLitehttp://www.sqlite.org is a small powerful self-contained, serverless, zero-configuration SQL database. Dump an d resto re It can be useful to dump and restore an SQLite database. For example you can edit the dump file to change a column attribute or type and then restore the database. This is easier than messing with SQL commands. Use the command sqlite3 for a 3.x database.
# sqlite database.db .dump > dump.sql # sqlite database.db < dump.sql # dump # restore

Conve rt 2. x to 3.x database

sqlite database_v2.db .dump | sqlite3 database_v3.db

DISK QUOTA
A disk quota allows to limit the amount of disk space and/or the number of files a user or (or member of group) can use. The quotas are allocated on a per -file system basis and are enforced by the kernel.

L i nu x s e tu p
The quota tools package usually needs to be installed, it contains the command line tools. Activate the user quota in the fstab and remount the partition. If the partition is busy, either all locked files must be closed, or the system must be rebooted. Add usrquota to the fstab mount options, for example:
/dev/sda2 /home reiserfs # mount -o remount /home # mount # quotacheck -vum /home # chmod 644 /home/aquota.user rw,acl,user_xattr,usrquota 1 1 # Check if usrquota is active, otherwise reboot

Initialize the quota.user file with quotacheck .


# To let the users check their own quota

Activate the quota either with the provided script (e.g. /etc/init.d/quotad on SuSE) or with quotaon :
quotaon -vu /home

Check that the quota is active with:


quota -v

F r e e BSD s e t up
The quota tools are part of the base system, however the kernel needs the option quota. If it is not there, add it and recompile the kernel.
options QUOTA /dev/ad0s1d # mount /home

As with Linux, add the quota to the fstab options (userquota, not usrquota):
/home ufs

Enable disk quotas in /etc/rc.conf and start the quota.


# grep quotas /etc/rc.conf enable_quotas="YES" check_quotas="YES" # /etc/rc.d/quota start

rw,noatime,userquota 2 2 # To remount the partition

# turn on quotas on startup (or NO). # Check quotas on startup (or NO).

As s i gn qu ot a l i m its
The quotas are not limited per default (set to 0). The limits are set with edquota for single users. A quota can be also duplicated to many users. The file structure is different between the quota implementations, but the principle is the same: the values of blocks and inodes can be limited. Only change the values of soft and hard . If not specified, the blocks are 1k. The grace period is set with edquota -t. For example:
# edquota -u colin

Linu x
Disk quotas for user colin (uid 1007): Filesystem blocks soft /dev/sda8 108 1000 hard 2000 inodes 1 soft 0 hard 0

FreeBS D
Quotas for user colin:

/home: kbytes in use: 504184, limits (soft = 700000, hard = 800000) inodes in use: 1792, limits (soft = 0, hard = 0)

Fo r man y use rs The command edquota -p is used to duplicate a quota to other users. For example to duplicate a reference quota to all users:
# edquota -p refuser `awk -F: '$3 > 499 {print $1}' /etc/passwd ` # edquota -p refuser user1 user2 # Duplicate to 2 users

Checks Users can check their quota by simply typing quota (the file quota.user must be readable). Root can check all quotas.
# quota -u colin # repquota /home # Check quota for a user # Full report for the partition for all users

SHELLS
Most Linux distributions use the bash shell while the BSDs use tcsh, the bourne shell is only used for scripts. Filters are very useful and can be piped:
y y y y y grep Pattern matching sed Search and Replace strings or characters cut Print specific columns from a marker sort Sort alphabetically or numerically uniq Remove duplicate lines from a file

For example used all at once:


# ifconfig | sed 's/ / /g ' | cut -d" " -f1 | uniq | grep -E "[a-z0-9]+" | sort -r # ifconfig | sed '/.*inet addr:/!d;s///;s/ .*//'|sort -t. -k1,1n -k2,2n -k3,3n -k4,4n

The first character in the sed pattern is a tab. To write a tab on the console, use ctrl -v ctrltab.

b as h
Redirects and pipes for bash and sh:
# # # # # # # cmd 1> file cmd 2> file cmd 1>> file cmd &> fil e cmd >file 2>&1 cmd1 | cmd2 cmd1 2>&1 | cmd2 # # # # # # # Redirect stdout to file. Redirect stderr to file. Redirect and append stdout to file. Redirect both stdout and stderr to file. Redirects stderr to stdout and then to file. pipe stdout to cmd2 pi pe stdout and stderr to cmd2

Modify your configuration in ~/.bashrc (it can also be ~/.bash_profile). The following entries are useful, reload with ". .bashrc".
# in .bashrc bind '"\e[A"':history -search-backward # Use up and down arrow to search bind '"\e[B"':history -search-forward # the history. Invaluable! set -o emacs # Set emacs mode in bash (see below) set bell-style visible # Do not beep, inverse colors # Set a nice prompt like [user@host]/path/todir> PS1="\[\033[1;30m \][\[\033[1;34m\]\u\[\033[1;30m\]" PS1="$PS1@ \[\033[0;33m\]\h\[\033[1;30m\]]\[\033[0;37m \]" PS1="$PS1 \w\[\033[1;30m \]>\[\033[0m\]" # To check the currently active aliases, simply type alias alias ls='ls -aF' # Append indica tor (one of */=>@|) alias ll='ls -aFls' # Listing alias la='ls -all' alias ..='cd ..'

alias ...='cd ../..' export HISTFILESIZE=5000 # Larger history export CLICOLOR=1 # Use colors (if possible) export LSCOLORS=ExGxFxdxCxDxDxBxBxExEx

t cs h
Redirects and pipes for tcsh and csh (simple > and >> are the same as sh):
# Redirect both stdout and stderr to file. # Append both stdout and stderr to file. # pipe stdout to cmd2 # pipe stdout and stderr to cmd2 The settings for csh/tcsh are set in ~/.cshrc , reload with "source .cshrc". Examples: # in .cshrc alias ls 'ls -aF' alias ll 'ls -aFls' alias la 'ls -all' alias .. 'cd ..' alias ... 'cd ../..' set prompt = "%B%n%b@%B%m%b%/> " # like user@host/path/todir> set history = 5000 set savehist = ( 6000 merge ) set autolist # Report possible completions with tab set visiblebell # Do not beep, inverse colors # Bindkey and colors bindkey -e Select Emacs bindings # Use emacs keys to edit the command prompt bindkey -k up history-search-backward # Use up and down arrow to search bindkey -k down history -search-forward setenv CLICOLOR 1 # Use colors (if possible) setenv LSCOLORS ExGxFxdxCxDxDxBxBxExEx # # # # cmd >& file cmd >>& file cmd1 | cmd2 cmd1 |& cmd2

The emacs mode enables to use the emacs keys shortcuts to modify the command prompt line. This is extremely useful (not only for emacs users). The most used commands are:
y y y y y y y y y y

C-a C-e M-b M-f M-d C-w C-u C-k C-y C-_

Move cursor to beginning of line Move cursor to end of line Move cursor back one word Move cursor forward one word Cut the next word Cut the last word Cut everything before the cursor Cut everything after the cursor (rest of the line) Paste the last thing to be cut (simply paste) Undo

Note: C- = hold control, M- = hold meta (which is usually the alt or escape key).

SCRIPTING
Basics | Script example | awk | sed | Regular Expressions | useful commands The Bourne shell (/bin/sh) is present on all Unix installations and scripts written in this language are (quite) portable; man 1 sh is a good reference.

Ba s i cs
Variables an d argume nts Assign with variable=value and get content with $variable
MESSAGE="Hello World" PI=3.1415 # Assign a string # Assign a decimal number

N=8 TWON=`expr $N * 2` TWON=$(($N * 2)) TWOPI=`echo "$PI * 2" | bc -l` ZERO=`echo "c($PI/4) -sqrt(2)/2" | bc -l`

# Arithmetic e xpression (only integers) # Other syntax # Use bc for floating point operations

The command line arguments are


$0, $1, $2, . .. $# $* # $0 is the command itself # The number of arguments # All arguments (also $@)

S peci al Variables
$$ $? command if [ $? != 0 ]; then echo "command failed" fi mypath=`pwd` mypath=${mypath}/file.txt echo ${mypath##*/} echo ${mypath%%.*} var2=${var:=string} # The current process ID # exit status of last command

# Display the filename only # Full path without extention # Use var if set, otherwise use string # assign string to var and then to var2.

Constructs
for file in `ls` do echo $file done count=0 while [ $count -lt 5 ]; do echo $count sleep 1 count=$(($count + 1)) done myfunction() { find . -type f -name "*.$1" -print } myfunction "txt" # $1 is first argument of the function

Gene rate a file


MYHOME=/home/colin cat > testhome.sh << _EOF # All of this goes into the file testhome.sh if [ -d "$MYHOME" ] ; then echo $MYHOME exists else echo $MYHOME does not exist fi _EOF sh testhome.sh

Bour ne s cr i p t e x a m p l e
As a small example, the script used to create a PDF booklet from this xhtml document:
#!/bin/sh # This script creates a book in pdf format ready to p rint on a duplex printer if [ $# -ne 1 ]; then # Check the argument echo 1>&2 "Usage: $0 HtmlFile" exit 1 # non zero exit if error

fi file=$1 fname=${file%.*} fext=${file#*.} # Assign the filename # Get the name of the file only # Get the extension of the file

prince $file -o $fname.pdf # from www.princexml.com pdftops -paper A4 -noshrink $fname.pdf $fname.ps # create postscript booklet cat $fname.ps |psbook|psnup -Pa4 -2 |pstops -b "2:0,1U(21cm,29.7cm)" > $fname.book.ps ps2pdf13 -sPAPERSIZE=a4 -sAutoRotatePages=None $fname.book.ps $fname.book.pdf # use #a4 and #None on Windows! exit 0 # exit 0 means successful

S om e a w k c om m a n d s
Awk is useful for field stripping, like cut in a more powerful way. Search this document f or other examples. See for example gnulamp.com and one-liners for awk for some nice examples.
awk awk awk awk awk '{ print $2, $1 }' file '{printf("%5d : %s \n", NR,$0)}' file '{print FNR " \t" $0}' files NF test.txt 'length > 80' # Print and inverse first two columns # Add line number left aligned # Add line number right aligned # remove blank lines ( same as grep '.') # print line longer than 80 char)

S om e s ed c om m a n ds
Here is the one liner gold minehttp://student.northpark.edu/pemente/sed/sed1line.txt. And a good introduction and tutorial to sedhttp://www.grymoire.com/Unix/Sed.html.
sed sed sed sed sed sed sed sed sed 's/string1/string2/g' -i 's/wroong/wrong/g' *.txt 's/\(.*\)1/\12/g' '/<p>/,/< \/p>/d' t.xhtml '/ *#/d; /^ *$/d' 's/[ \t]*$//' 's/^[ \t]*//;s/[ \t]*$//' 's/[^*]/[&]/' = file | sed 'N;s/ \n/\t/' > file.num # Replace string1 wit h string2 # Replace a recurring word with g # Modify anystring1 to anystring2 # Delete lines that start with <p> # and end with </p> # Remove comments and blank lines # Remove trailing spaces (use tab as \t) # Remove leading and trailing spaces # Enclose first char with [] top ->[t]op # Number lines on a file

Re g ul ar Ex pr es s i on s
Some basic regular expression use ful for sed too. See Basic Regex Syntaxhttp://www.regularexpressions.info/reference.html for a good primer.
[\^$.|?*+() themselves \ * . .* ^ $ .$ line/string ^ $ [^A-Z] Z # special characters any other will match # escapes special characters and treat as literal # repeat the previous item zero or more times # single character except line break c haracters # match zero or more characters # match at the start of a line/string # match at the end of a line/string # match a single character at the end of # match line with a single space # match any line beginning with any char from A to

S om e us e ful c om m a n d s
The following commands are useful to include in a script or as one liners.
sort -t. -k1,1n -k2,2n -k3,3n -k4,4n echo 'Test' | tr '[:lower:]' '[:upper:]' echo foo.bar | cut -d . -f 1 # Sort IPv4 ip addresses # Case conversion # Returns foo

PID=$(ps | grep script.sh | grep bin | awk '{print $1}') # PID of a running script PID=$(ps axww | grep [p]ing | awk '{print $1}') # PID of ping (w/o grep pid) IP=$(ifconfig $INTERFACE | sed '/.*inet addr:/!d;s///;s/ .*//') # Linux IP=$(ifconfig $INTERFACE | sed '/.*inet /!d;s///;s/ .*//') # FreeBSD if [ `diff file1 file2 | wc -l` != 0 ]; then [...] fi # File changed? cat /etc/master.passwd | grep -v root | grep -v \*: | awk -F":" \ # Create http passwd '{ printf("%s:%s \n", $1, $2) }' > /usr/local/etc/apache2/passwd testuser=$(cat /usr/local/etc/apache2/passwd | grep -v \ # Check user in passwd root | grep -v \*: | awk -F":" '{ printf("%s \n", $1) }' | grep ^user$) :(){ :|:& };: # bash fork bomb . Will kill your machine tail +2 file > file2 # remove the first line from file

I use this little trick to change the file extension for many files at once. For example from .cxx to .cpp. Test it first without the | sh at the end. You can also do this with the command rename if installed. Or with bash builtins.
# # # # ls *.cxx | awk -F. '{print "mv "$0" "$1".cpp"}' | sh ls *.c | sed "s/.*/cp & &.$(date "+%Y%m%d")/" | sh # e.g. copy *.c to *.c.20080401 rename .cxx .cpp *.cxx # Rename all .cxx to cpp for i in *.cxx; do mv $i ${i%%.cxx}.cpp; done # with bash builtins

PROGRAMMING
C b as i cs
strcpy(newstr,str) expr1 ? expr2 : expr3 x = (y > z) ? y : z; int a[]={0,1,2}; int a[2][3]={{1,2,3},{4,5,6}}; int i = 12345; char str[10]; sprintf(str, "%d", i); /* /* /* /* /* /* copy str to newstr */ if (expr1) expr2 else expr3 */ if (y > z) x = y; else x = z; */ Initialized array (or a[3]={0,1,2}; */ Array of array of int s */ Convert in i to char str */

C example
A minimal c program simple.c:
#include <stdio.h> main() { int number=42; printf("The answer is %i \n", number); }

Compile with:
# gcc simple.c -o simple # ./simple The answer is 42

C+ + b a s i cs
*pointer &obj obj.x pobj->x // Object pointed to by pointer // Address of object obj // Member x of class obj (object obj) // Member x of class pointed to by pobj // (*pobj).x and pobj ->x are the same

C+ + e x a m p l e
As a slightly more realistic program in C++: a class in its own header (IPv4.h) and implementation (IPv4.cpp) and a program which uses the class functionality. The class converts an IP address in integer format to the known quad format.

IP v4 class IPv4.h:
#ifndef IPV4_H #define IPV4_H #include <string> namespace GenericUtils { // create a namespace class IPv4 { // class definition public: IPv4(); ~IPv4(); std::string IPint_to_IPquad(unsigned long ip);// member interface }; } //namespace GenericUtils #endif // IPV4_H

IPv4. cpp:
#include "IPv4.h" #include <string> #include <sstream> using namespace std; using namespace GenericUtils; IPv4::IPv4() {} IPv4::~IPv4() {} string IPv4::IPint_to_IPquad(unsigned long ip) { ostringstream ipstr; ipstr << ((ip &0xff000000) >> 24) << "." << ((ip &0x00ff0000) >> 16) << "." << ((ip &0x0000ff00) >> 8) << "." << ((ip &0x000000ff)); return ipstr.str(); }

// use the namespaces // default constructor/destructor // member implementation / / use a stringstream // Bitwise right shift

The pro gram sim ple cpp.cpp


#include "IPv4.h" #include <iostream> #include <string> using namespace std; int main (int argc, char* argv[]) { string ipstr; unsigned long ipint = 1347861486; GenericUtils::IPv4 iputils; ipstr = iputils.IPint_to_IPquad(ipint); cout << ipint << " = " << ipstr << endl; return 0; }

// // // // //

define variables The IP in integer form create an object of the class call the class member print the result

Compile and execute with:


# g++ -c IPv4.cpp simplecpp.cpp # Compile in objects # g++ IPv4.o simplecpp.o -o simplecpp.exe # Link the objects to final executable # ./simple cpp.exe 1347861486 = 80.86.187.238 Use ldd to check which libraries are used by the executable and where they are located. Also

used to check if a shared library is missing or if the executable is static.


# ldd /sbin/ifconfig # ar rcs staticlib.a *.o # ar t staticlib.a archive # ar x /usr/lib/libc.a version.o archive # nm version.o object # list dynamic object dependencies # create static archive # print the objects list from the # extract an object file from the

# show function members provided by

Si m p l e M a k e fi l e
The minimal Makefile for the multi -source program is shown below. The lines with instructions must begin with a tab! The back slash "\" can be used to cut long lines.
CC = g++ CFLAGS = -O OBJS = IPv4.o simplecpp.o simplecpp: ${OBJS} ${CC} -o simplecpp ${CFLAGS} ${OBJS} clean: rm -f ${TARGET} ${OBJS}

ONLINE HELP
D oc u m en t a ti on
en.tldp.org Linux Man Pages www.linuxmanpages.com Linux commands directory www.oreillynet.com/linux/cmd Linux doc man howtos linux.die.net FreeBSD Handbook www.freebsd.org/handbook FreeBSD Man Pages www.freebsd.org/cgi/man.cgi Linux Documentation FreeBSD user wiki Solaris Man Pages www.freebsdwiki.net docs.sun.com/app/docs/coll/40.10

O th er U n i x /L i n u x r e fer en c es
Rosetta Stone for Unix Unix guide cross reference Linux commands line list Short Linux reference bhami.com/rosetta.html (a Unix command translator)

unixguide.net/unixguide.shtml www.linuxcmd.org www.pixelbeat.org/cmdline.html Little command line goodies www.shell-fu.org That's all folks! This document: "Unix Toolbox revision 14.1" is licensed under a Creative Commons Licence [Attribution - Share Alike]. Colin Barschel 2007-2009. Some rights reserved.

Anda mungkin juga menyukai