Sei sulla pagina 1di 60

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

a 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. 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 tem po o sistema est executando, ou seja, quanto 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 Lin ux) # man hier # Descrio da hierarquia dos arquivos no siste ma # last reboot # Exibe o histrico da reinicializao do sistema Informao do Hardware Hardware detectado no kernel # dmesg # Hardware detectado e mensagens de inicializao # lsdev # Informao sobre a instalao do hardware # dd if=/dev/mem bs=1k skip=768 count=256 2>/dev/null | strings -n 8 # Leitura d a BIOS Linux # 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 om suas propriedades # dmidecode FreeBSD # sysctl hw.model # sysctl hw # sysctl vm # dmesg | grep "real mem" # sysctl -a | grep mem el # sysctl dev # pciconf -l -cv # usbdevs -v # atacontrol list # camcontrol devlist -v # # # # # # # # # # 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 c

# # # # # # # #

# Mostra DMI/SMBIOS: como a informao da BIOS # Mostra o modelo da CPU Mostra vrias informaes do hardware Memria usada Memria do hardware Configuraes e informaes sobre a memria do kern Mostra os dispositivos configurados Exibe dispositivos PCI Exibe dispositivos USB Exibe dispositivos ATA Exibe dispositivos SCSI

Load, estatsticas e mensagens Os comandos a seguir so usados para localizar o que est acontecendo no sistema. # top # Exibe e atualiza os processos da CPU # mpstat 1 # Exibe os processos das capacidades relaci onadas # vmstat 2 # a capacidade da memria virtual # iostat 2 # Exibe a capacidade I/O (2s intervalo) # systat -vmstat 1 # Resumo da capacidade do sistema BSD (1s i ntervalo) # systat -tcp 1 # Conexes tcp no BSD (tenta tambm ip) # systat -netstat 1 # Ativa as conexes de rede BSD # systat -ifstat 1 # BSD trfego de redes ativas # systat -iostat 1 # BSD taxa de transferncia do disco e da CPU # tail -n 500 /var/log/messages # As ltimas 500 linhas mensagens do registro # tail /var/log/warn # Mensagens de alerta do sistema, veja em s yslog.conf # Exibe o id, usurio e grupo ati vo # 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 # Adiciona um usurio ao grupo (Debian) # groupmod -A # Adiciona um usurio ao grupo (SuSE) # userdel colin # Exclui o usurio Colin # adduser joe # FreeBSD, adiciona o usurio ao sistema (int erativamente) # rmuser joe # FreeBSD, deleta o usurio joe (interativame nte) # 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 Senhas criptografadas esto armazenadas no /etc/shadow nos Linux e Sol aris, no FreeBSD esto localizadas no /etc/master.passwd. Se o master.passwd for modifi cado manualmente (deleta a senha), executa # pwd_mkdb -p master.passwd para repor o b anco de dados. Para prevenir amplos acessos temporrios (para todos os usurios mas root) use nologin. A mensagem do nologin ser Exibido (talvez no trabal ha com as chaves ssh). # echo "Desculpe no acessa agora" > /etc/nologin # (Linux ) # echo "Desculpe no acessa agora" > /var/run/nologin # (FreeBSD) Limites 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.Linux Cada Shell/script O limite do Shell regido por um ulimit. O estado c hecado com ulimit -a. Por exemplo, para trocar os arquivos limites dos 1024 para Usurios # id

10240 faa: # ulimit -n 10240 Shell

# Isso apenas validar dentro do

O comando ulimit pode ser usado no em um script para trocar os limit es do script apenas.Por usurio/processoAcesso de aplicaes e usurios podem ser configurados no /etc/security/limits.conf. Por exemplo: # cat /etc/s ecurity/limits.conf * hard nproc 250 # Limites de processos por usurios asterisk hard nofile 409600 # Aplicaes limites de arquivos abertos Sistema amploLimites do kernel so ajustados sysctl. Limites permanent es so ajustados no /etc/sysctl.conf. # sysctl -a # Visualiza todo o limite do sistema # sysctl fs.file-max # Visualiza o limite mximo de arquivos abert os # sysctl fs.file-max=102400 # Troca o limite mximo # echo "1024 50000" > /proc/sys/net/ipv4/ip_local_port_range #Faixa de portas # 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 FreeBSD Cada Shell/script Use o comando limits em csh ou tcsh ou igual ao Linux, use ulimit no bash shell. Por usurio/processo O padro dos limites de acesso so configurados no /etc/login.conf. Um valor ilimit ado ainda limitado pelo sistema de valor mximo. Sistema amploLimites do k ernel 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 si stema # 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 # Padro 1024-5000 # netstat -m # Capacidade de memria da rede Veja o FreeBSD handbook Chapter 11 para detalhes. Solaris Seguindo os valores no /etc/system incrementar o mximo de descries por proc:: set rlim_fd_max = 4096 # L imite fsico nos arquivos de descries para o nico proc set rlim_fd_cur = 1024 # Limite lgico nas filas descritas para o nic o proc Runlevels Linux Uma vez iniciado o kernel inicia o init que ento comea o rc que inicia todos os scripts pertencente a um runlevel. O scri pts so armazenados em um /etc/init.d e so ligados 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 alterado com init. Por exemplo para ir do 3 para o 5: # init 5 0 1 2 3 5 6 # Entra o runlevel 5 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 --list # Lista todos os scripts do ini t # chkconfig --list sshd # chkconfig sshd --level 35 on # chkconfig sshd off omando update-rc.d para gerenciar o script do runlevel. Por padro comea e m 2,3,4 e 5 e shutdown no # Ativa sshd como runlevel padro # update-rc.d sshd start 20 2 3 4 5 # update-rc.d -f sshd remove # shutdown -h now (or # poweroff) ls. 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 runle vels. Por exemplo 0 1 6 c q # init 6 para reiniciar. 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) 0,1 e 6. # update-rc.d sshd defaults . stop 20 0 1 6 . # Com argumentos explcitos # Desabilita sshd para todos runlevels # Desliga o sistema ou suspende # 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 c

FreeBSD O boot do BSD se aproxima do sistema SysV, no existem runleve

Zerar senha de Root Linux mtodo 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 # ou deleta a senha de root no (/etc/shadow ) # sync; mount -o remount,ro / # sync depois de remontar para somente leit ura # reboot FreeBSD mtodo 1No FreeBSD, inicia o single-user, remonta / rw e a sen ha. 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 # montar / rw # passwd # reboot Unixes e FreeBSD e Linux mtodo 2 Outros Unixes no poderia deix-lo ir em bora com o truque simples init. A soluo montada na partio de outro SO (como u m CD) e troca a senha no disco. Inicia o CD live ou a instalao em um modo de recuperao que vai lhe d ar um Shell Procura a partio root com fdisk /dev/sda Monta e usa o chroot # mount -o rw /dev/ad4s3a /mnt # chroot /mnt # chroot into /mnt # passwd # reboot Mdulos do Kernel Linux # lsmod os # modprobe isdn FreeBSD # kldstat s # kldload crypto Compilando o Kernel Linux # cd /usr/src/linux # make mrproper # make oldconfig # make menuconfig # make # make modules # make modules_install # make install # reboot

# lista todos os mdulos carregad # Carrega um mdulo #Lista todos os mdulos carregado # Para carregar um mdulo

# # # # # # #

Limpa o antigo .config se existir Re-usa o antigo .config se existente ou xconfig (Qt) ou gconfig (GTK) Cria uma imagem comprimida Compila os mdulos Instala os mdulos Instala o kernel

FreeBSD Atualizao opcional de origem (em /usr/src) com csup (como FreeBSD 6.2 ou posterior): # csup Eu sigo o supfile: *default host=cvsup5.FreeBSD.org # www.freebsd.org/handbook/cvsup.h tml#CVSUP-MIRRORS *default prefix=/usr *default base=/var/db *default release=cvs delete tag=RELENG_7 src-all 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 formad os. # # # # # cd /usr/src/sys/i386/conf/ cp GENERIC MYKERNEL cd /usr/src make buildkernel KERNCONF=MYKERNEL make installkernel KERNCONF=MYKERNEL Para a reconstruo total SO: # make buildworld nel # make buildkernel # make installkernel # reboot # mergemaster -p conhecidos # make installworld # mergemaster -i -U ivos # reboot a reconstruo de toda a rvore.# make buildworld NO_CLEAN=yes eta os objetos antigos # make buildkernel KERNCONF=MYKERNEL NO_CLEAN=yes # No del # Constri total o SO mas no o ker

# Usa KERNCONF para ambos # Compare somente os arquivos essenciais e # Atualiza todas as configuraes e outros arqu

Para pequenas alteraes no fonte, voc pode usar NO_CLEAN=yes para evitar

# # # #

Repara o Grub 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 # Monta a partio linux em /mnt mount --bind /proc /mnt/proc # monta o subsistema proc no /mnt mount --bind /dev /mnt/dev # monta os dispositivos no /mnt chroot /mnt # troca a partio root Linux grub-install /dev/sda # reinstala grub com suas antigas configuraes

Processos Listando | Prioridade | Background/Foreground | Top | Kill Listagem e PIDs 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 pro cessos em execuo

No entanto o uso mais tpico com o pipe ou o pgrep: # ps axww | grep c ron 586 ?? Is 0:01.48 /usr/sbin/cron -s # ps axjf # Todos processos 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 (Lin ux) # pmap PID # Mapa dos processos em memria (Caa vazamento s 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/Unixwa re Prioridade 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/nic e) # nice -n 5 top # nice +5 top # Prioridade fraca (/usr/bin/nice) # tcsh tem nice embutido (mesmo que acima!)

Enquanto o nice altera o agendamento da CPU, um outro comando til o i onice, ir fixar o IO do disco. Isto muito til para aplicaes intensivas (ex. compilao). Vo ce pode selecionar uma classe (ociosa - melhor esforo - tempo real ), a pgina do manual curta e bem explicativa. # ionice c3 -p123 # ajusta a classe ociosa para o PID 123 (Linux Somente) # ionice -c2 -n0 firefox # Executa o firefox com melhor esforo e maio r prioridade # ionice -c3 -p$$ # Ajusta o shell atual para prioridade ocio sa O ultimo comando muito til para compilar (ou debugar) um longo projet o. Cada comando iniciado neste shell ter a prioridade herdada. $$ o seu shell pid (te nte echo $$). FreeBSD usa idprio/rtprio (0= mxima ke # Compila com # idprio 31 -1234 # idprio -t -1234 al/ociosa prioridade, 31 = mais inativo) # idprio 31 ma menor prioridade # Ajusta o PID 1234 com menor prioridade # -t remove qualquer prioridade de tempo re

Background/Foreground Quando iniciado a partir de um shell, os processos podem ser levados ao background e ao foreground com [Ctrl]

-[Z] (^Z), ^Z bg e fg. Lista os processos com jobs. # ping cb.vu > ping.log # ping interrompido (parado) com [Ctrl]-[Z]

# bg # Coloca em segundo plano e continua execut ando # 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 pl ano Use nohup para iniciar o processo que tem que continuar a executar q uando 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/ht op/). Enquanto o top executado pressione a tecla "h" para uma viso geral da ajuda. Teclas teis so: 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. Signals/Kill 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 por www Kill cada processo acessando /home (para

Sinais importantes so: 1 HUP (desliga) 2 INT (suspende) 3 QUIT (fecha) 9 KILL (fora) 15 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 Permisses 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/escr eve | 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] MODO[,MODO] ARQUIVO # MODO na forma [ugoa]*([-+=]([rw xXst])) # 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 para outros para todos os usurios # chmod u+s /path/to/prog # Fixa SUID bit no executvel (saiba o que es ta fazendo!) # find / -perm -u+s -print # Localiza todos os programas com o SUID bi t # chown user:group /path/to/file # Altera a propriedade do usurio e o grupo n o 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 d iretrios Informao de Disco # diskinfo -v /dev/ad2 amanho) FreeBSD # hdparm -I /dev/sda # fdisk /dev/ad2 # smartctl -a /dev/ad2 # Informao sobre o disco (Setor/t # Informao sobre o disco IDE/ATA (Linux) # Exibe e manipula a tabela de parties # O SMART exibe as informao do disco

Boot FreeBSD Para inicializar o antigo kernel se o novo kernel no iniciali zar, pare o boot durante a contagem regressiva# unload # load kernel.old # boot Sistema de ponto de montagem/Uso de disco # mount | column -t # Exibe o sistema de arquivos m ontados no seu sistema # df # Exibe o espao livre no disco e dispositivo s montados # cat /proc/partitions # Exibe todas parties registradas (Linux) Uso de Disco # du -sh * # du -csh # du -ks * | sort -n -r # ls -lSr # Lista o tamanho dos diretrios # Tamanho total do diretrio corrente # Ordena tudo por tamanho em kilobytes # Exibe arquivos, maiores por ltimo

Quem tem arquivos abertos Este muito til para localizar quem esta bloqueando a partio e tem que ser desmontado e recebe um erro tpic o:# umount /home/ umount: unmount of /home # Impossvel desmontar porque um arquivo esta bloqueando o home Falhou: Dispositivo Ocupado

FreeBSD e maioria dos Unixes # fstat -f /home # Para montar o ponto # fstat -p PID # Para uma aplicao com PID # fstat -u user # Para um nome de usurio Localiza arquivos de log aberto (ou outros arquivos abertos), pela p alavra Xorg: # ps ax | grep Xorg | awk '{print $1}' 1252 # fstat USER root root root -p 1252 CMD Xorg Xorg Xorg PID FD MOUNT 1252 root / 1252 text /usr 1252 0 /var INUM 2 216016 212042 MODE SZ|DV R/W drwxr-xr-x 512 r -rws--x--x 1679848 r -rw-r--r-- 56987 w

O arquivo com inum 212042 o nico arquivo em /var: # find -x /var -inu m 212042 /var/log/Xorg.0.log Linux Localiza arquivos abertos em um ponto de montagem: fuser ou lsof: # fuser -m /home # Lista os processos acessando o /home # lsof /home COMMAND PID USER FD tcsh 29029 eedcoba cwd ome) lsof 29140 eedcoba cwd ome) TYPE DEVICE DIR 0,18 DIR 0,18 SIZE NODE NAME 12288 1048587 /home/eedcoba (guam:/h 12288 1048587 /home/eedcoba (guam:/h

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

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 Montando e Remontando um Sistema de Arquivos Por exemplo, o cdrom. Se listado em /etc/fstab # mount /cdrom Ou localize o dispositivo em /dev ou com o dmesgFreeBSD # mount -v -t cd9660 /dev/cd0c /mnt # cdrom # mount_cd9660 /dev/wcd0c /cdrom # outro mtodo # mount -v -t msdos /dev/fd0c /mnt # disquete Entrada no /etc/fstab: # Device Mountpoint Pass# /dev/acd0 /cdrom FStype Options 0 0 Dump

cd9660 ro,noauto

Para permitir o usurio fazer: # sysctl vfs.usermount=1 # Ou inserir a linha "vfs.usermount=1" em /etc/sysctl.conf Linux # mount -t auto /dev/cdrom /mnt/cdrom # Tpico comando para montar c

drom # mount /dev/hdc -t iso9660 -r /cdrom # Tpico IDE # mount /dev/scd0 -t iso9660 -r /cdrom # Tpico SCSI cdrom # mount /dev/sdc0 -t ntfs-3g /windows # Tpico SCSI Entrada no /etc/fstab: /dev/cdrom /media/cdrom subfs noauto,fs=cd fss,ro,procuid,nosuid,nodev,exec 0 0 Montar uma Partio FreeBSD com Linux Localize o nmero da partio com fdisk, esta geralmente a partio root, mas poderia ser outro slice BSD tambm. S e 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/sda # Local iza 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 Remontar Remontar um dispositivo sem desmontar. Necessrio para fsck por exemplo # mount -o remount,ro / # Linux # mount -o ro / # FreeBSD Copie os dados brutos a partir do cdrom em uma imagem iso: # dd if=/ dev/cd0c of=file.iso Adicionar swap em tempo real 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 # Ative a swap. Agora em uso! # swapoff /swap2gb # Quando terminar, desative a swap # rm /swap2gb Montar um Compartilhamento SMB Suponha que ns queremos acessar o compartilhamento SMB em um computador smbserver, o endereo digitado e m um computador Windows \\smbserver\myshare. Ns montamos em /mnt/smbshare. Alerta> ci fs precisa de um IP ou nome DNS, no um nome Windows. Linux # smbclient -U user -I 192.168.16.229 -L //smbshare/ # Lista os c ompartilhamentos # mount -t smbfs -o username=winuser //smbserver/myshare /mnt/smbshare # mount -t cifs -o username=winuser,password=winpwd //192.168.16.229/myshare /mn t/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 FreeBSD Use -I para pegar o IP (ou nome DNS); smbserver o nome Windo ws. # smbutil view -I 192.168.16.229 //winuser@smbserver # List os compartilh amentos # mount_smbfs -I 192.168.16.229 //winuser@smbserver/myshare /mnt/smbshare Montar uma imagem Voltando ao Linux # mount -t iso9660 -o loop file.iso /mnt

# Monta uma

imagem de CD # mount -t ext3 -o loop file.img /mnt istema de arquivos ext3

# Monta uma imagem com s

FreeBSD 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 /dev/vn0c file.iso; mount -t cd9660 /dev /vn0c /mnt # umount /mnt; vnconfig -u /dev/vn0c # Limpeza do dispositivo vn Solaris e FreeBSD Voltando ao incio com a interface do arquivo ou lof i: # lofiadm -a file.iso # mount -F hsfs -o ro /dev/lofi/1 /mnt # umount /mnt; lofiadm -d /dev/lofi/1 # Limpeza do dispositivo lofi Criar e Queimar uma imagem ISO 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 p ara 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 com eando 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 u ma imagem ISO de CD/DVD FreeBSD 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. # bur ncd -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. Ferramen tas dvd+rw O dvd+rw-tools pacote (FreeBSD: ports/sysutils/dvd+rw-tools) pode fazer tudo e incl ui 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/c0t1d0s2 (Exemplo de um dispositivo Solaris SCSI/ATAPI

CD-ROM ). Existe uma boa documentao com exemplos em FreeBSD handbook chapter 18.7. # -dvd-compat finaliza o disco # growisofs -dvd-compat -Z /dev/dvd=imagefile.iso # Queima uma imagem iso ex istente # growisofs -dvd-compat -Z /dev/dvd -J -R /p/to/data # Queima diretamente Converter um arquivo do Nero .nrg para .iso O nero simplesmente adic iona um cabealho de 300Kb para uma imagem iso normal. Isto pode ser mudado co m o dd. # dd bs=1k if=imagefile.nrg of=imagefile.iso skip=300 Converter uma imagem /bin/cue para .iso O pequeno bchunk program pod e fazer isso. E no ports do FreeBSD em sysutils/bchunk. # bchunk imagefile.bin imagefile.cue imagefile.iso Criar um arquivo baseado em uma imagem Por exemplo, uma partio de 1GB usando o arquivo /usr/vdisk.img. Aqui usamos o vnode 0, mas t ambm poderia ser o 1. FreeBSD # dd if=/dev/random of=/usr/vdisk.img bs=1K count=1M # mdconfig -a -t vnode -f /usr/vdisk.img -u 0 # Cria o dispositivo /dev/ md1 # bsdlabel -w /dev/md0 # newfs /dev/md0c # mount /dev/md0c /mnt # umount /mnt; mdconfig -d -u 0; rm /usr/vdisk.img # Cleanup the md device

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/mdc onfig 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 exe utada 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" /etc/rc.conf: # mdconfig_md0="-t vnode -f /usr/vdisk.img" # /usr is not o n the root partition /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 # A maior partio de arquivos agora 300MB Linux # 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; rm /usr/vdisk.img

# Limpeza

Linux with losetup /dev/zero muito mais rpido urandom, mas menos segura para criptografia # dd if=/dev/urandom of=/usr/vdisk.img bs=1024k count=1 024 # losetup /dev/loop0 /usr/vdisk.img 0 # mkfs.ext3 /dev/loop0 # mount /dev/loop0 /mnt # losetup -a ados # umount /mnt # losetup -d /dev/loop0 # rm /usr/vdisk.img # Cria e associa /dev/loop

# Verifica os loops utiliz # Separa

Criar um Sistema de Arquivos de Memria 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:FreeBSD # mount_mfs -o rw -s 64M md /memdisk # umount /memdisk; mdconfig -d -u 0 # Limpeza do dispositivo m d md /memdisk mfs rw,-s64M 0 0 # entrada /etc/fstab Linux # mount -t tmpfs -osize=64m tmpfs /memdisk Desempenho de Disco 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 Debugging (Veja mais Traffic analysis) Linux # ethtool eth0 # Mostra o estado da ethernet (substitui # # # o # mii-diag) ethtool -s eth0 speed 100 duplex full # Fora 100Mbit Full duplex ethtool -s eth0 autoneg off # Desabilita auto negociao ethtool -p eth1 # Pisca o led da ethernet - muito til quando suportad # Mostra todas as interfaces no Linux (semelhante ao # Levanta o dispositivo (ou desce). O mesmo que "ifc # Mostra todos os endereos IP no linux (semelhante ao # Semelhante ao arp -a

ip link show ifconfig) # ip link set eth0 up onfig eth0 up" # ip addr show ifconfig) # ip neigh show Outros OS's

# ifconfig fxp0 # Verifica o campo "media" no FreeBSD # arp -a # Verifica o Roteador (ou host) entrada ARP (todos O S) # 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 (Free BSD) # 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 firewal ls Roteamento Imprimindo Tabela de Roteamento # route -n # Linux ou use "ip route" # netstat -rn # Linux, BSD and UNIX # route print # Windows Adiciona e Deleta Rotas FreeBSD # 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 netmask 255.255.255.0 gw 192.168.16.25 4 # 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 o prxim o gateway # route change default 192.168.50.254 1 Entradas permanentes so estabelecidas em /etc/defaultrouter. 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. Configure Endereos IP adicionais Linux # ifconfig eth0 192.168.50.254 netmask 255.255.255.0 # Primeir o IP # ifconfig eth0:0 192.168.51.254 netmask 255.255.255.0 # Segundo IP # ip addr add 192.168.50.254/24 dev eth0 # Equivalente ao coma ndo ip # ip addr add 192.168.51.254/24 dev eth0 label eth0:1

# Primeir o 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 ap elido 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 up # Second IP Alterar Endereo MAC Normalmente voc tem que derrubar a relao antes da mudana. No me diga porque voc quer mudar o endereo MAC ... # ifconfig eth0 down ifconfig eth0 hw ether 00:01:02:03:04:05 # Linux ifconfig fxp0 link 00:01:02:03:04:05 # FreeBSD ifconfig hme0 ether 00:01:02:03:04:05 # Solaris sudo ifconfig en0 ether 00:01:02:03:04:05 # Mac OS X Tiger sudo ifconfig en0 lladdr 00:01:02:03:04:05 # Mac OS X Leopard

FreeBSD # ifconfig fxp0 inet 192.168.50.254/24

# # # # #

Muitas ferramentas existentes para Windows. Por Exemplo etherchange. Ou procure por "Mac Makeup", "smac". Portas em Uso 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 Firewall Verificando se o firewall esta executando.Linux # iptables -L -n -v # Status Open the iptables firewall # iptables -P INPUT ACCEPT # Abre tudo # iptables -P FORWARD ACCEPT # iptables -P OUTPUT ACCEPT # iptables -Z # Zera os contadores de pacotes para todas as regras # iptables -F # Limpa todas as Regras # iptables -X # Deleta todas as Regras FreeBSD # ipfw show # Status # ipfw list 65535 # if answer is "65535 deny ip from any to any" the fw is disab led # sysctl net.inet.ip.fw.enable=0 # Disable # sysctl net.inet.ip.fw.enable=1 # Enable Encaminhamento IP para Roteamento Linux Verifica e habilita o encaminhamento do IP com: # cat /proc/sys/net/ipv4/ip_forward # Verifica o IP encaminhado 0=o ff, 1=on

# echo 1 > /proc/sys/net/ipv4/ip_forward ou edita /etc/sysctl.conf com: net.ipv4.ip_forward = 1 FreeBSD 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 gate way. Solaris # ndd -set /dev/ip ip_forwarding 1 ento 0=off, 1=on # Defina o IP para o encaminham

NAT Network Address Translation Linux # iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE var o NAT # iptables -t nat -A PREROUTING --to 192.168.16.44:22 # iptables -t nat -A PREROUTING --to 192.168.16.254:993-995 # ip route flush cache # iptables -L -t nat -p tcp # Port -p tcp # Port

# Para ati

-d 78.31.70.238 --dport 20022 -j DNAT \ forward 20022 to internal IP port ssh -d 78.31.70.238 --dport 993:995 -j DNAT \ forward of range 993-995

# Check NAT status

Deleta a porta para o encaminhamento com -D em vez de -A.FreeBSD # 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 # Faixa de porta redirect_port udp 192.168.51.103:7777 7777 DNS No Unix o DNS so vlidos para todas as interfaces e armazenadas no /etc/resolv.conf. O domnio para qual a mquina pertence tambm armazen ado no arquivo. A configurao mnima : nameserver 78.31.70.238 search sleepyowl.net intern.lab domain sleepyowl.net Verifica o nome do domnio no sistema com: # hostname -d # Igual ao dnsdomainname Windows No Windows o DNS so configurados pela interface. Para que exi ba a configurao DNS e para limpar o cache do DNS usa-se: # ipconfig /? # Exibe ajuda # ipconfig /all # Veja toda a informao incluindo o DNS Limpa o DNSLimpe o cache DNS do SO, alguns aplicativos usa seu prprio cache (ex. Firefox).

r # # #

# /etc/init.d/nscd restart # Reinicia nscd, se utiliza - Linux/BSD/Solaris lookupd -flushcache # OS X Tiger dscacheutil -flushcache # OS X Leopard and newer ipconfig /flushdns # Windows Encaminhe as Consultas 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) ouca entrada pode ser requerida e o servidor de DNS pode selecionar com @: # dig MX google.com # dig @127.0.0.1 NS sun.com # Para teste o local do servidor # dig @204.97.212.10 NS MX heise.de # Consulta externa do servidor # dig AXFR @ns1.xname.org cb.vu # Obtenha a zona cheia(zona de transferncia) O programa da mquina tambm poderoso. # host -t MX cb.vu # Obtenha o mail MX de entrada # host -t NS -T sun.com # Obtenha o NS da conexo TCP. # host -a sleepyowl.net # Obtenha qualquer coisa Consultas Inversas 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 /etc/hosts 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 exempl78.31.70.238 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\DR IVERS\ETC DHCP Linux Algumas distribuies (SuSE) usa dhcpcd como cliente. O padro eth0. # dhcpcd -n eth0 # Provocar uma renovao( no sempre funciona) # dhcpcd -k eth0 # lanamento e encerramento O arrendamento com a total informao so armazenadas no:/var/lib/dhcpcd/d hcpcd-eth0.info FreeBSD FreeBSD (e Debian) usa dhclient. Para configurar a interface (por exemplo bge0) executa: # dhclient bge0 O arrendamento com a total in formao so armazenados no: /var/db/dhclient.leases.bge0 Usa /etc/dhclient.conf para preceder as opes ou forar as diferentes opes: # c sleepyowl.net sleepyowl 78.31.70.238

O roteador 192.168.51.254 respondeu e responsvel pela entrada do A. P

at /etc/dhclient.conf interface "rl0" { prepend domain-name-servers 127.0.0.1; default domain-name "sleepyowl.net"; supersede domain-name "sleepyowl.net"; } Windows O dhcp pode ser renovado com ipconfig: # ipconfig /renew # renova todos os adaptadores # ipconfig /renew LAN # renew the adapter named "LAN" # ipconfig /release WLAN # release the adapter named "WLAN" Sim isto uma boa idia para renomear seu adaptador com simples nomes! Anlise de Trfego Bmon um pequeno console da largura de bandas e pode exibir o fluxo de diferentes interfaces. Sniff com tcpdump # tcpdump -nl -i bge0 not port ssh and src \(192.168.16.121 or 192.1 68.16.54\) # tcpdump -n -i eth1 net 192.168.16.121 # select to/from a single IP # tcpdump -n -i eth1 net 192.168.16.0/24 # select traffic to/from a net work # tcpdump -l > dump && tail -f dump # Buffered output # tcpdump -i rl0 -w traffic.rl0 # Write traffic headers in bin ary file # tcpdump -i rl0 -s 0 -w traffic.rl0 # Write traffic + payload in b inary file # tcpdump -r traffic.rl0 # Read from file (also for eth ereal # tcpdump port 80 # The two classic commands # tcpdump host google.com # tcpdump -i eth0 -X port \(110 or 143\) # Check if pop or imap is secu re # tcpdump -n -i eth0 icmp # Only catch pings # tcpdump -i eth0 -s 0 -A port 80 | grep GET # -s 0 for full packet -A for ASCII

Adiciona importante opes: -A Imprime cada pacotes na limpeza do texto (sem cabealho) -X Imprime pacotes em hex e ASCII -l 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 lista r as interfaces. Scan com nmap 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 portas reservadas TCP na mqu ina # 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 pac ote IP assembler/analyzer e fping (fping.sourceforge.net). fping pode ch ecar multiplos rund-robin fashion. Controle de trfego (QoS) 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. lim ite uploadLimite de upload Modens DSL ou de cabo tm uma longa fila pa ra melhorar o rendimento upload. No entanto preenchendo a fila com um d ispositivo rpido (ethernet, por exemplo) ir diminuir drasticamente a interatividade. P or conseguinte, til para limitar a taxa de upload dispositivo para coincidir com a ca pacidade 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 qdisc add dev eth0 root tbf rate 480kbit latency 50ms burst 1540 # tc -s qdisc ls dev eth0 # Status # tc qdisc del dev eth0 root # Delete the queue # tc qdisc change dev eth0 root tbf rate 220kbit latency 50ms burst 1540 FreeBSD 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 t ubo reconfigurar isto. Por exemplo o limite do upload da largura da banda para 500 Kb it. # kldload dummynet # carrega os mdulos se necessrio # ipfw pipe 1 config bw 500Kbit/s # cria um tubo com limitado pe la largura da banda # ipfw add pipe 1 ip from me to any # diverte todos os upload tambm pelo tubo Qualidade de Servio Linux 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 co m QoS0x1e (todos os bits). O padro do fluxo em 3 filas e QoS Mnimo-atraso fluxo em 2 filas. # 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 o

s servidores match ip dst 123.23.0.1 flowid 1:1

# e/ou usa IP do servidor

Status and remove with # tc -s qdisc ls dev eth0 # status da fila # tc qdisc del dev eth0 root # 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) lizando 2^14 = 16384 # echo "obase=16;(2^14)-1024" | bc # mask is 0x3C00 # fina

# # # # # # #

ipfw ipfw ipfw ipfw ipfw ipfw ipfw

FreeBSD O max largura da banda 500Kbit/s e ns definimos 3 filas com a prioridade 100:10:1 para VoIP:ssh:all the rest. # 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 e remove com # ipfw list # status das regras # ipfw pipe list # ipfw flush adro

# status do tubo # deleta todas as regras por p

# # # #

NIS Debugging Alguns comandos que deveria trabalhar ser bem configuradas NIS cliente: # ypwhich # Obtem a conexo NIS do servidor de nomes domainname # Configura o nome do domnio NIS ypcat group # Mostra o grupo do servidor NIS cd /var/yp && make # Reconstri o yp banco de dados rpcinfo -p servername # 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 1190635041. Seg Sep 24 13:57:21 2007 O servio master servername.domain.net. Linux # cat /etc/yp.conf ypserver nomeservidor domain domain.net broadcast Netcat Netcat (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 [...] e here.

Voc precisa usar comandos netcat em vez de nc. Tambm veja um comando similar socat. Transferncia de arquivo Copia a largura do diretrio sobre uma cone xo. 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 serv idor, e coloque isso no cliente. Aqui 192.168.1.1 o endereo do servidor. server# tar -cf - -C VIDEO_TS . | nc -l -p 4444 # Diretrio tar na porta do servidor 4 444 client# nc 192.168.1.1 4444 | tar xpf - -C VIDEO_TS # Puxa o arquivo na port a 4444 server# cat largefile | nc -l 5678 # O nico arquivo client# nc 192.168.1.1 5678 > largefile # Puxa o nico arquivo server# dd if=/dev/da0 | nc -l 4444 # Imagem da partio client# nc 192.168.1.1 4444 | dd of=/dev/da0 # Puxa a partio para o clo ne client# nc 192.168.1.1 4444 | dd of=da0.img # Puxa a partio para o arq uivo 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 -l p 4444 -e /bin/bash # Fornece um shell remoto (servidor c landestino) # nc -lp 4444 -e cmd.exe # shell remoto para Windows Servidor de emergncia 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 te xto transferido com a chave de entrada. alice# nc -lp 4444 bob # nc 192.168.1.1 4444

SSH SCP Chave Pblica | Fingerprint | SCP | Tunelamento Autenticao por chave pblica Conecte na mquina sem senha utilizando a autenticao por chave pblica. A idia acrescentar sua chave pb lica para a authorized_keys2 arquivo na mquina remota. Para isso veja o ex emplo: 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 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 servid or ~/.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"

Utilizando o cliente Windows ssh.com A verso no comercial do cliente s sh.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 Cria o par de chaves com o cliente ssh.com: Configuraes - Autentic ao 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 ta mbm o ~/.ssh diretrio. As chaves esto no C:\Documents and Settings\%USERNAME%\Applicatio n 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 po r senha. Usando o putty para Windows Putty simples e livre o cliente ssh para Windows. 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/ Usa o comando ssh-keygen no servidor para converter a chave para OpenSSH: # cd ~/.ssh # ssh-keygen -i -f puttykey.pub >> authorized_keys2 Ponto da chave privada localizada nas configuraes putty: Conexo - S SH Auth Checa fingerprint No primeiro login, ssh perguntar se a mquina for desconhecida com o fingerprint tem que ser armazenada no n a mquina desconhecida. Para evitar um man-in-the-middle ataque o administrado r 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 R SA 2048 61:33:be:9b:ae:6c:36:31:fd:83:98:b7:99:2d:9f:cd /etc/ssh/ssh_host_rsa_key.p ub # 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.p ub 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 Transferncia segura de arquivos 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 sist ema 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 sshfs. Tunelame nto Tunelamento SSH permite o encaminhamento ou reverte para frente de u ma porta atravs da conexo SSH, garantindo assim o trfego e o acesso das portas que de out ra fora so bloqueadas. Isso s com TCP. A nomenclatura geral para o encaminhament o 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 local encaminha para o s eu 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 desthos t: destport. Nota 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 port a para o encaminhamento possvel.Encaminha direto para a porta Vamos dizer que ns queremos acessar o CVS (porta 2401) e http (porta 80) que esto execut ando 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 ser o roo t. Primeiro a sesso ssh aberta, ambos os services so acessveis nas portas locais. # s sh -L 2401:localhost:2401 -L 8080:localhost:80 usuario@porta Netbios e desktop remoto encaminham para um segundo servidor Vamos d izer que um servidor smb Windows a porta est por trs e no est executando o ssh. Ns pr ecisamos de acesso ao compartilhamento SMB e desktop remoto tambm para o servi dor. # ssh -L 139:smbserver:139 -L 3388:smbserver:3389 usuario@porta O compartilhamento SMB pode agora ser acessado com \\127.0.0.1\, mas s omente se o local do compartilhamento desabilitado, porque o local do compartilhamento ou vido na porta

139. Isto possvel para manter o local compartilhado habilitado, para isso ns precisamos criar um novo dispositivo virtual com um novo ende reo IP para o tunelamento, o compartilhamento smb conectar atravs do endereo. Alm diss o o local RDP est pronto para ser ouvido na porta 3389, ento ns escolhemos 33 88. Para isso vamos usar um IP virtual 10.1.1.1. 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 por ta 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: # Sistema->Painel de Controle->Adicionar Hardware # Sim, Hardwar e est pronto para ser conectado # Adiciona um novo hardware (em baixo). # Instala o hardware que manualmente selecionado # Adaptador de Rede # Microsoft , Microsoft Adaptador Loopback. Configura o endereo IP do dispositivo falso para 10.1.1.1 mask 25 5.255.255.0, sem gateway. avanado->WINS, Habilita LMHosts Lookup; Desabilita NetBIOS sobre TCP/IP. # Habilita Cliente para Microsoft redes. # Desabilita compartilh amento de arquivo e impressora para a rede Microsoft. Tive que reiniciar para esse trabalho. Agora conecta para o compart ilhamento com \\10.1.1.1 e o desktop remoto para 10.1.1.1:3388. Debug Se no funcion ar 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 Microsoft " 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 loc almente, a opo GatewayPorts no necessrio. No cliente cliusuario (de destino para a porta): # ssh -R 2022:localhost:22 usuario@porta # encaminha o cl iente 22 para a porta: 2022 No cliente cliadmin (da mquina da porta): # ssh -L 3022:localhost:2022 admin@porta # encaminha o clien te 3022 para a porta:2022 Agora o administrador pode ligar diretamente para o cliente cliusuar io com: # ssh -p 3022 admin@localhost # local:3022 -> porta:20 22 -> cliente:22 Conecta com VNC por trs do NAT Suponhamos um cliente Windows VNC escu tando na porta 5900 tem que ter o acesso por trs do NAT. No cliente cliwin a p orta: # ssh -R 15900:localhost:5900 user@gate On client cliadmin (from hos t to gate): # ssh -L 5900:localhost:15900 admin@gate Agora o administrado r pode conectar diretamente ao cliente VNC com: # vncconnect -display :0 lo calhost Escave um tnel ssh multi-hop Suponhamos que voc no possa alcanar o servidor diretamente com ssh, mas somente atravs de vrias mqui nas (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 a rquivos 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 lpul o. 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 p ara um servidor mais de dois saltos. Uma vez que o tnel construdo, possvel se conectar ao se rvidor diretamente do cliente (e tambm adiciona outra porta para o encaminha mento).Criando tnel no shell cliente -> maquina1 -> maquina2 -> servidor e escav ar tnel 5678 cliente># ssh -L5678:localhost:5678 mquina1 # 5678 um a porta arbitraria para o tnel maquina_1># ssh -L5678:localhost:5678 mquina2 # sequncia 5678 da mquina1 par a a mquina2 maquina_2># ssh -L5678:localhost:22 servidor # No final do tnel na porta 22 no servidor Utilizando tnel com outro shell cliente -> usando o tnel 5678 no servi dor # ssh -p 5678 localhost # conecta diretamente do cli ente para o servidor # scp -P 5678 myfile localhost:/tmp/ # ou copia o arquivo diretamente utilizando o tnel # rsync -e 'ssh -p 5678' myfile localhost:/tmp/ # ou rsync o arquivo diretamente para o servidor

Autoconnect script e manter vivoEu uso as variaes do script a seguir p ara manter uma mquina alcanveis por um tnel SSH reverso. A conexo automaticam ente reconstruda se fechado. Voc pode adicionar vrios -L or -R tneis em uma linha. #!/bin/sh COMMAND="ssh -N -f -g -R 3022:localhost:22 colin@cb.vu" pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND exit 0 1 * * * * colin /home/colin/port_forward.sh qui a cada hora) # crontab entrada (a

VPN com SSH A partir da verso 4.3, o OpenSSH pode usar o dispositivo tun/tap para encriptar um tunnel. Isto muito semelhante a outras sol ues VPN baseada em TLS como o OpenVPN. Uma vantagem com o SSH que no h a necessidade d e instalar e configurar um software adcional. Alm disso o tunel utiliza a autentic ao 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 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 arqui vo sshd_conf: PermitRootLogin yes PermitTunnel yes Conexo P2P nica 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: Conectar com SSH usando o tnel, opo-w Configure os endereos IP do tnel. Uma vez no servidor e uma vez o cliente. Conectar ao servidor Conexo iniciada no cliente e os comandos so execu tados no servidor.Linux o Servidor cli># ssh -w5:5 root@hserver srv># ifconfig tun5 10.0.1.1 netmask 255.255.255.252 ervidor FreeBSD o Servidor cli># ssh -w5:5 root@hserver srv># ifconfig tun5 10.0.1.1 10.0.1.2 ervidor # Executada no shell do s

# Executada no shell do s

Configure o Cliente Comandos executados no cliente: cli># ifconfig tun5 10.0.1.2 netmask 255.255.255.252 Linux

# Cliente um

cli># ifconfig tun5 10.0.1.2 10.0.1.1

# Cliente um FreeBSD

Os dois hosts esto conectados de forma transparente e podem se comuni car com qualquer protocolo de camada 3/4 usando os endereos IP do tnel.Conectar Duas Redes Alm da instalao p2p acima, mais til conectar duas redes provad as com uma VPN SSH usando dois gateways. Supondo o exemplo, netA 192.16 8.51.0/24 e netB 192.168.16.0/24. O procedimento semelhante ao citado acima, ns precis amos 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) 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 ex ecutados em gatewayBGatewayB o Linux gatewayA># ssh -w5:5 root@gateB gatewayB># ifconfig tun5 10.0.1.1 netmask 255.255.255.252 # Executada no shell d o 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 GatewayB o FreeBSD gatewayA># ssh -w5:5 root@gateB spositivo 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 no for padro gatewayB># natd -s -m -u -dynamic -n fxp0 gatewayA># sysctl net.inet.ip.fw.enable=1 # Cria o di # Executada no shell do # Somente necessrio se o # veja NAT

Configure GatewayA Comando executado no GatewayAGatewayA o Linux gatewayA># ifconfig tun5 10.0.1.2 netmask 255.255.255.252 gatewayA># route add -net 192.168.16.0 netmask 255.255.255.0 dev tun5 gatewayA># echo 1 > /proc/sys/net/ipv4/ip_forward gatewayA># iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE GatewayA o FreeBSD 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

gatewayA># gatewayA># gatewayA># gatewayA>#

# veja NAT

Agora as duas redes privadas esto conectadas transparentemente via VP

N SSH. O NAT soemten necessrio se os gateways no forem o padro da rede. Neste caso o s clientes no sabem para onde encaminhar a resposta,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/ # modo "arquiv o". manter o mesmo # rsync -a /var/ /var_bak/ # rsync -aR --delete-during /home/user/ /backup/ # utilizao relativa (veja ab aixo) 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 sh ell remota Excluir qualquer diretrio tmp dentro de /home/user/ e manter a hierar quia de pastas relativa, que o diretrio remoto ter a estrutura /backup/home/user/. Is to tipicamente usado para backups. # rsync -azR --exclude=tmp/ /home/user/ user@server:/backup/ Usa a p orta 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, porm no encriptografados p or ssh. A localizao do /backup definido pela configurao em /etc/rsyncd.conf. A var ivel RSYNC_PASSWORD pode ser ajustado para evitar a necessidade de digita r a senha manualmente. # rsync -axSRz /home/ ruser@hostname::rmodule/backup/ # rsync -axSRz ruser@hostname::rmodule/backup/ /home/ # Para copiar de volta Algumas opes importantes: -a, --archive modo arquivo; mesmo que -rlptgoD (sem -H) -r, --recursive recursivo em diretrios -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 Rsync em Windows Rsync est disponvel para Windows atravs do Cygwin ou empacotado em cwrsync. Isto muito conveniente para backups automatizados. Instalar um deles (not both) e adicione o caminho para as variveis do sistema Windows: # Painel de c ontrole -> Sistema -> aba Avanado, boto Variveis de Ambiente. Edite a "Pasta" variv eis de sistema e adicione o caminho completo para o rsync instalado, exempl o: C:\Program Files\cwRsync\bin ou C:\cygwin\bin. Desta forma os comandos rsync e ssh esto disponveis no shell do Windows.Autenticao via Chave Pblica Rsync automaticamente encapsulada por SSH e, portanto, usa a autenticao no servidor SSH. os backups automticos para evitar a interao d o usurio usa autenticao SSH via chave pblica e pode ser usado o comando rsync qu e 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 authori zed_keys2 ainda no existe, basta copiar id_dsa.pub para authorized_keys2 e carreg-lo. # ssh-keygen -t dsa -N '' # Cria a chave pblica e p rivada # rsync user@server:.ssh/authorized_keys2 . # Copia o arquivo localmente do serv er # cat id_dsa.pub >> authorized_keys2 # Ou usar um editor para adicionar a chave # rsync authorized_keys2 user@server:.ssh/ # Copia o arquivo de volta para o se rver # del authorized_keys2 # Remove a cpia local Agora teste com (em uma linha): rsync -rv "/cygdrive/c/Documents and Settings/%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 -> Ferramenta s do Systema -> Tarefas Agendadas). Por exemplo crie o arquivo backup.bat e subst itua 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 o ut 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 restart # Run the rc script as root # sudo -u sysadmin whoami # Run cmd as an other user Configuration Sudo is configured in /etc/sudoers and must only be edited with visudo. The basi c syntax is (the lists are comma separated): user hosts = (runas) commands # 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 enclos ed 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/sudoers # 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 pas sword. DEVEL DESKTOP = (ALL) NOPASSWD: ALL # Developers have full right on de sktops DEVEL DMZ = (ALL) NOPASSWD: DEBUG # Developers can debug the DMZ ser vers. # 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 us er. # anyone can mount/unmount a cd-rom on the desktop machines ALL DESKTOP = NOPASSWD: /sbin/mount /cdrom,/sbin/umount /cdrom

Encrypt Files OpenSSL A single 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 and encrypt a whole directory # 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 and encrypt a whole directory # tar -zcf - directory | openssl aes-128-cbc -salt -out directory.tar.gz.aes # Encrypt # openssl aes-128-cbc -d -salt -in directory.tar.gz.aes | tar -xz -f # Decrypt

Use -k mysecretpassword after aes-128-cbc to avoid the interactive password requ est. However note that this is highly insecure. Use aes-256-cbc instead of aes-128-cbc to get even stronger encryption. This use s also more CPU. GPG 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 enc rypted with a password and anyone who knows the password can decrypt it, thus th e keys are not needed. Gpg adds an extention ".gpg" to the encrypted file names. # gpg -c file # Encrypt file with password # gpg file.gpg # Decrypt file (optionally -o otherfile) Using keys For more details see GPG Quick Start and GPG/PGP Basics and the gnupg documentat ion among others. The private and public keys are the heart of asymmetric cryptography. What is im portant to remember: 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 publi c 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 usef ul 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 Windows they are typically stored i n C:/Documents and Settings/%USERNAME%/Application Data/gnupg/. ~/.gnupg/pubring.gpg # Contains your public keys and all others imported ~/.gnupg/secring.gpg # Can contain more than one private key Short reminder on most used options: -e -d -r -a -o encrypt data decrypt data NAME encrypt for recipient NAME (or 'Full Name' or 'email@domain') create ascii armored output of a key use as output file

The examples use 'Your Name' and 'Alice' as the keys are referred to by the emai l or full name or partial name. For example I can use 'Colin' or 'c@cb.vu' for m y key [Colin Barschel (cb.vu) ]. Encrypt for personal use only No need to export/import any key for this. You have both already. # gpg -e -r 'Your Name' file # Encrypt with your public key # gpg -o file -d file.gpg # Decrypt. Use -o or it goes to st dout Encrypt - Decrypt with keys First you need to export your public key for someone else to use it. And you nee d 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 -a -o alicekey.asc --export 'Alice' # Alice exported her key in ascii file. # gpg --send-keys --keyserver subkeys.pgp.net KEYID # Alice put her key on a s erver. # gpg --import alicekey.asc # You import her key into your pub ring. # gpg --search-keys --keyserver subkeys.pgp.net 'Alice' # or get her key from a server. Once the keys are imported it is very easy to encrypt or decrypt a file: # gpg -e -r 'Alice' file # Encrypt the file for Alice. # gpg -d file.gpg -o file # Decrypt a file encrypted by Alic e for you. Key administration # gpg --list-keys IDS The KEYID follows the '/' e.g. for: pub CE # gpg --gen-revoke 'Your Name' # gpg --list-secret-keys # gpg --delete-keys NAME ey ring # gpg --delete-secret-key NAME # list public keys and see the KEY 1024D/D12B77CE the KEYID is D12B77 # generate revocation certificate # list private keys # delete a public key from local k # delete a secret key from local k

ey ring # gpg --fingerprint KEYID # gpg --edit-key KEYID ail)

# Show the fingerprint of the key # Edit key (e.g sign or add/del em

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 th e methods I know and use. Keep in mind that the security is only good as long th e OS has not been tempered with. An intruder could easily record the password fr om the keyboard events. Furthermore the data is freely accessible when the parti tion is attached and will not prevent an intruder to have access to it in this s tate. Linux 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 other 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. T he device mapper uses labels to identify a partition. We use sdc1 in this exampl e, 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 L UKS is available, simply type # cryptsetup --help, if nothing about LUKS shows u p, use the instructions below Without LUKS. First create a partition if necessar y: fdisk /dev/sdc. Create encrypted partition # dd if=/dev/urandom of=/dev/sdc1 # Optional. For paranoids only (takes days) # cryptsetup -y luksFormat /dev/sdc1 # This destroys any data on sdc1 # cryptsetup luksOpen /dev/sdc1 sdc1 # mkfs.ext3 /dev/mapper/sdc1 # create ext3 file system # mount -t ext3 /dev/mapper/sdc1 /mnt # umount /mnt # cryptsetup luksClose sdc1 # Detach the encrypted partition Attach # cryptsetup luksOpen /dev/sdc1 sdc1 # mount -t ext3 /dev/mapper/sdc1 /mnt Detach # umount /mnt # cryptsetup luksClose sdc1 dm-crypt without LUKS # cryptsetup -y create sdc1 /dev/sdc1 op0 # dmsetup ls 0) # mkfs.ext3 /dev/mapper/sdc1 # mount -t ext3 /dev/mapper/sdc1 /mnt # umount /mnt/ # cryptsetup remove sdc1 # or any other partition like /dev/lo # check it, will display: sdc1 (254, # 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. FreeBSD The two popular FreeBSD disk encryption modules are gbde and geli. I now use gel

i because it is faster and also uses the crypto device for hardware acceleration . See The FreeBSD handbook Chapter 18.6 for all the details. The geli module mus t be loaded or compiled into the kernel: options GEOM_ELI device crypto # or as module: # echo 'geom_eli_load="YES"' >> /boot/loader.conf # or do: kldload geom_eli Use password and key I use those settings for a typical disk encryption, it uses a passphrase AND a k ey to encrypt the master key. That is you need both the password and the generat ed key /root/ad1.key to attach the partition. The master key is stored inside th e partition and is not visible. See below for typical USB or file based image. Create encrypted partition # dd if=/dev/random of=/root/ad1.key bs=64 count=1 r key # geli init -s 4096 -K /root/ad1.key /dev/ad1 ks # geli attach -k /root/ad1.key /dev/ad1 ad1.key # dd if=/dev/random of=/dev/ad1.eli bs=1m time # newfs /dev/ad1.eli # mount /dev/ad1.eli /mnt Attach # geli attach -k /root/ad1.key /dev/ad1 # fsck -ny -t ffs /dev/ad1.eli stem # mount /dev/ad1.eli /mnt # this key encrypts the mate # -s 8192 is also OK for dis # DO make a backup of /root/ # Optional and takes a long # Create file system

# In doubt check the file sy

Detach The detach procedure is done automatically on shutdown. # umount /mnt # geli detach /dev/ad1.eli /etc/fstab The encrypted partition can be configured to be mounted with /etc/fstab. The pas sword will be prompted when booting. The following settings are required for thi s 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 0 0 Use password only It is more convenient to encrypt a USB stick or file based image with a passphra se 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 k ey file. Let's encrypt a file based image /cryptedfile of 1 GB. # dd if=/dev/zero of=/cryptedfile bs=1M count=1000 # 1 GB file # mdconfig -at vnode -f /cryptedfile # geli init /dev/md0 # encrypts with password onl y # geli attach /dev/md0 # newfs -U -m 0 /dev/md0.eli # mount /dev/md0.eli /mnt # umount /dev/md0.eli

# geli detach md0.eli 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

SSL Certificates So called SSL/TLS certificates are cryptographic public key certificates and are composed of a public and a private key. The certificates are used to authentica te the endpoints and encrypt the data. They are used for example on a web server (https) or mail server (imaps). Procedure 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 certifica te (the public part) and already contains all necessary information. The certifi cate request is normally sent to the authority vendor for signing. This step als o 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.). Configure OpenSSL We use /usr/local/certs as directory for this example check or edit /etc/ssl/ope nssl.cnf accordingly to your settings so you know where the files will be create d. Here are the relevant part of openssl.cnf: [ CA_default ] dir = /usr/local/certs/CA # Where everything is kept certs = $dir/certs # Where the issued certs are kept crl_dir = $dir/crl # Where the issued crl are kept database = $dir/index.txt # database index file. Make sure the directories exist or create them # mkdir -p /usr/local/certs/CA # cd /usr/local/certs/CA # mkdir certs crl newcerts private # echo "01" > serial # Only if serial does not exist # touch index.txt If you intend to get a signed certificate from a vendor, you only need a certifi cate signing request (CSR). This CSR will then be signed by the vendor for a lim ited time (e.g. 1 year). Create a certificate authority 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 r equest. To make a certificate authority (CA): # openssl req -new -x509 -days 730 -config /etc/ssl/openssl.cnf \ -keyout CA/private/cakey.pem -out CA/cacert.pem Create a certificate signing request

To make a new certificate (for mail server or web server for example), first cre ate a request certificate with its private key. If your application do not suppo rt 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 al so created the private key newkey.pem. Sign the certificate The certificate request has to be signed by the CA to be valid, this step is usu ally 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.pem # mv newkey.pem servernamekey.pem Now servernamekey.pem is the private key and servernamecert.pem is the server ce rtificate. Create united certificate The IMAP server wants to have both private key and server certificate in the sam e file. And in general, this is also easier to handle, but the file has to be ke pt securely!. Apache also can deal with it well. Create a file servername.pem co ntaining both the certificate and key. Open the private key (servernamekey.pem) with a text editor and copy the priva te 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/: 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! View certificate information 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 certificat

CVS Server setup | CVS test | SSH tunneling | CVS usage Server setup Initiate the CVS Decide where the main repository will rest and create a root cvs. For example /u sr/local/cvs (as root): # mkdir -p /usr/local/cvs # setenv CVSROOT /usr/local/cvs # Set CVSROOT to the new location (local) # cvs init # Creates all internal CVS config files # cd /root # cvs checkout CVSROOT # Checkout the config files to modify them # cd CVSROOT edit config ( fine as it is) # cvs commit config cat >> writers # Create a writers file (optionally also re aders) colin ^D # Use [Control][D] to quit the edit # cvs add writers # Add the file writers into the repository # cvs edit checkoutlist # cat >> checkoutlist writers ^D # Use [Control][D] to quit the edit # cvs commit # 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, but rather checkout the fi le, modify it and check it in. We did this with the file writers to define the w rite 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 u se them: Direct local access to the file system. The user(s) need sufficient file permi ssion to access the CS directly and there is no further authentication in additi on 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 accoun t 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 o n 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 by the CVS pserver with a d edicated password database, there is therefore no need for local users accounts. This setup is explained below. Network setup 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/i netd.conf (/etc/xinetd.d/cvs on SuSE): cvspserver stream tcp nowait cvs /usr/bin/cvs cvs \ --allow-root=/usr/local/cvs pserver

It is a good idea to block the cvs port from the Internet with the firewall and use an ssh tunnel to access the repository remotely. Separate authentication 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. Simply add a file named passwd (in the CVSROOT directory) containing the users login and p assword 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 C VSROOT 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 t o cvs (or whatever your cvs server is running under). It looks like this: # cat passwd user1:xsFjhU22u8Fuo:cvs user2:vnefJOsnnvToM:cvs Test 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:

CVSROOT variable This is an environment variable used to specify the location of the repository w e'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 specifi ed. Set the CVSROOT variable with setenv CVSROOT string on a csh, tcsh shell, or with export CVSROOT=string on a sh, bash shell. # setenv CVSROOT :pserver:@:/cvsdirectory For example: # setenv CVSROOT /usr/local/cvs # Used locally onl y # setenv CVSROOT :local:/usr/local/cvs # Same as above # setenv CVSROOT :ext:user@cvsserver:/usr/local/cvs # Direct access wi th SSH # setenv CVS_RSH ssh # for the ext acce ss # setenv CVSROOT :pserver:user@cvsserver.254:/usr/local/cvs # network with pse rver When the login succeeded one can import a new project into the repository: cd into your project root directory cvs import cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs import MyProject MyCompany S TART 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 tunneling for CVS We need 2 shells for this. On the first shell we connect to the cvs server with ssh and port-forward the cvs connection. On the second shell we use the cvs norm ally as if it where running locally. on shell 1: # ssh -L2401:localhost:2401 colin@cvs_server # Connect directly to the CVS ser ver. Or: # ssh -L2401:cvs_server:2401 colin@gateway # 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 commands and usage Import 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 s ubdirectories 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 importe d too. # cd /devel/tools # cvs import myapp/tools Company R1_0 Checkout update add commit # cvs co myapp/tools # cvs co -r R1_1 myapp ) # cvs -q -d update -P # cvs update -A # cvs add newfile # cvs add -kb newfile # cvs commit file1 file2 # cvs commit -m "message" # Will only checkout the directory tools # Checkout 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 development directory re lated 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 fi le # diff -Naur oldfile newfile > patchfile Apply a patch Sometimes it is necessary to strip a directory level from the patch, depending h

ow it was created. In case of difficulties, simply look at the first lines of th e patch and try -p0, -p1 or -p2. # cd /devel/project # patch --dry-run -p0 < patchfile # Test the path without applying it # patch -p0 < patchfile # patch -p1 < patchfile # strip off the 1st level from the path

SVN Server setup | SVN+SSH | SVN over http | SVN usage Subversion (SVN) is a version control system designed to be the successor of CVS (Concurrent Versions System). The concept is similar to CVS, but many shortcomi ngs where improved. See also the SVN book. Server setup The initiation of the repository is fairly simple (here for example /home/svn/ m ust exist): # svnadmin create --fs-type fsfs /home/svn/project1 Now the access to the repository is made possible with: file:// Direct file system access with the svn client with. This requires loca l permissions on the file system. svn:// or svn+ssh:// Remote access with the svnserve server (also over SSH). T his requires local permissions on the file system (default port: 2690/tcp). http:// Remote access with webdav using apache. No local users are necessary f or 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 dir ectory, simply give the full path: # svn import /project1/ file:///home/svn/project1/trunk -m 'Initial import' # svn checkout file:///home/svn/project1 The new directory "trunk" is only a convention, this is not required. Remote access with ssh No special setup is required to access the repository via ssh, simply replace fi le:// with svn+ssh/hostname. 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 (wit h 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 repo sitory, for example: # groupadd subversion # groupmod -A user1 subversion # chown -R root:subversion /home/svn # chmod -R 770 /home/svn Remote access with http (apache) Remote access over http (https) is the only good solution for a larger user grou p. This method uses the apache authentication, not the local accounts. This is a typical but small apache configuration: LoadModule dav_module modules/mod_dav.so LoadModule dav_svn_module modules/mod_dav_svn.so LoadModule authz_svn_module modules/mod_authz_svn.so # Only for access cont rol 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 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 Access control svn.acl example # 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 SVN commands and usage See also the Subversion Quick Reference Card. Tortoise SVN is a nice Windows int erface. Import A new project, that is a directory with some files, is imported into the reposit ory with the import command. Import is also used to add a directory with its con tent 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 new dir' Typical SVN commands # svn co http://host.url/svn/project1/trunk # Checkout the most recent vers ion # Tags and branches are created by copying # svn mkdir http://host.url/svn/project1/tags/ # Create the tags directory # svn copy -m "Tag rc1 rel." http://host.url/svn/project1/trunk \ http://host.url/svn/project1/tags/1.0rc1 # svn status [--verbose] # Check files status into worki ng dir # svn add src/file.h src/file.cpp # Add two files # svn commit -m 'Added new class file' # Commit the changes with a mes sage # svn ls http://host.url/svn/project1/tags/ # List all tags # svn move foo.c bar.c # Move (rename) files # svn delete some_old_file # Delete files

Useful Commands less | vi | mail | tar | dd | screen | find | Miscellaneous less 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]): h H 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 u seful to know some basic commands. There are two modes: command mode and inserti on mode. The commands mode is accessed with [ESC], the insertion mode with i. Us e : help if you are lost. The editors nano and pico are usually available too and are easier (IMHO) to use . Quit :w newfilename save the file to newfilename :wq or :x save and quit :q! quit without saving Search and move /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 text 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 mail The mail command is a basic application to read and send email, it is usually in stalled. 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. Example: # 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. tar The command tar (tape archive) creates and extracts archives of file and directo ries. 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 ar e: Create # cd / # tar -cf home.tar home/ # archive the whole /home directory (c for creat e) # tar -czf home.tgz home/ # same with zip compression # tar -cjf home.tbz home/ # same with bzip2 compression Only include one (or two) directories from a tree, but keep the relative structu re. For example archive /usr/local/etc and /usr/local/www and the first director y in the archive should 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 st) # tar -xf home.tar # tar -xzf home.tgz ression) # look inside the archive without extracting (li # extract the archive here (x for extract) # same with zip compression (-xjf for bzip2 comp

# remove leading path gallery2 and extract into gallery # tar --strip-components 1 -zxvf gallery2.tgz -C gallery/ # tar -xjf home.tbz home/colin/file.txt # Restore a single file More advanced # tar c dir/ | gzip tely. # tar cvf - `find . ry. # tar -cf - -C /etc # tar -cf - -C /etc opy. # tar -czf home.tgz | ssh user@remote 'dd of=dir.tgz' # arch dir/ and store remo -print` > backup.tar # arch the current directo

. | tar xpf - -C /backup/etc # Copy directories . | ssh user@remote tar xpf - -C /backup/etc # Remote c --exclude '*.o' --exclude 'tmp/' home/

dd The program dd (disk dump or destroy disk or see the meaning of dd) is used to c opy partitions and disks and for other copy tricks. Typical usage: # dd if= of= bs= conv= Important conv options: notrunc ros. noerror sync do not truncate the output file, all zeros will be written as ze continue after read errors (e.g. bad blocks) 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 restore # 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=1M if=/dev/ad4s3e | gzip -c > ad4s3e.gz # Zip the backu p # gunzip -dc ad4s3e.gz | dd of=/dev/ad0s3e bs=1M # Restore the z ip # dd bs=1M if=/dev/ad4s3e | gzip | ssh eedcoba@fry 'dd of=ad4s3e.gz' # also remo te # 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. Recover The command dd will read every single block of the partition. In case of problem s 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 bloc k size equal or smaller than the disk block size. A 1k size seems safe, set it w ith bs=1k. If a disk has bad sectors and the data should be recovered from a par tition, 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 remot e 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 sta te # The above is useful to refresh a disk. It is perfectly safe, but must be unm ounted. Delete # dd if=/dev/zero of=/dev/hdc # dd if=/dev/urandom of=/dev/hdc # kill -USR1 PID # kill -INFO PID D) # # # # Delete full disk Delete full disk better View dd progress (Linux) View dd progress (FreeBS

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 partiti on 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 lo ader # dd if=/mbr_sda.bak of=/dev/sda bs=1 count=64 skip=446 seek=446 # Restore parti tion table

screen Screen (a must have) has two main functionalities: Run multiple terminal session within a single terminal. A started program is decoupled from the real terminal and can thus run in the ba ckground. The real terminal can be closed and reattached later. Short start example 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 deta ch and logout remotely first. If it was not running create it and notify the use r. Or: # screen -x Attach to a running screen in a multi display mode. The console is thus shared a mong multiple users. Very useful for team work/debug! Screen commands (within screen) All screen commands start with Ctrl-a. 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. Find Some important options: -x (on BSD) -xdev (on Linux) . -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 b elow. # find / -name "*.core" | xargs rm # Find core dumps and delete them (also try core.*) # find / -name "*.core" -print -exec rm {} \; # Other syntax # Find images and create an archive, iname is not case sensitive. -r for a Stay on the same file system (dev in fstab)

ppend # find {} \; # find iles # find # find # find # find ts

. \( -iname "*.png" -o -iname "*.jpg" \) -print -exec tar -rf images.tar . -type f -name "*.txt" ! -name README.txt -print # Exclude README.txt f /var/ -size +10M -exec ls -lh {} \; # Find large files > 10 MB /var/ -size +10M -ls # This is simpler . -size +10M -size -50M -print /usr/ports/ -name work -type d -print -exec rm -rf {} \; # Clean the por

# 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 ret urn wrong results when files or directories contain spaces. In doubt use "-print 0 | xargs -0" instead of "| xargs". The option -print0 must be the last in the f ind command. See this nice mini tutorial for find. # 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 Miscellaneous # 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 wo rd # whereis java # Search path and standard directories for word # setenv varname value # Set env. variable varname to value (csh/t csh) # export varname="value" # set env. variable varname to value (sh/ks h/bash) # pwd # Print working directory # mkdir -p /path/to/dir # no error if existing, 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 /dir2 # Archive and hard link files instead of co py # cp -lpR /dir1 /dir2 # Same for FreeBSD # cp unixtoolbox.xhtml{,.bak} # Short way to copy the file with a new ext ension # 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 md5su m 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

Install Software Usually the package manager uses the proxy variable for http/ftp requests. In .b ashrc: export http_proxy=http://proxy_server:3128 export ftp_proxy=http://proxy_server:3128 List installed packages # rpm -qa sed) # dpkg -l # pkg_info # pkg_info -W smbd o # pkginfo # List installed packages (RH, SuSE, RPM ba # Debian, Ubuntu # FreeBSD list all installed packages # FreeBSD show which package smbd belongs t # Solaris

Add/remove software Front ends: yast2/yast for SuSE, redhat-config-packages for Red Hat. # rpm -i pkgname.rpm # install the package (RH, SuSE, RPM based) # rpm -e pkgname # Remove package Debian # apt-get update # apt-get install emacs # dpkg --remove emacs # dpkg -S file # # # # First update the package lists 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 # First sync the local portage tree # emerge -u packagename # Install or upgrade a package # emerge -C packagename # Remove the package # revdep-rebuild # Repair dependencies Solaris The path is usually /cdrom/cdrom0. # pkgadd -d /Solaris_9/Product SUNWgtar # pkgadd -d SUNWgtar # Add downloaded package (bunzip2 first) # pkgrm SUNWgtar # Remove the package FreeBSD # pkg_add -r rsync # pkg_delete /var/db/pkg/rsync-xx # Fetch and install rsync. # Delete the rsync package

Set where the packages are fetched from with the PACKAGESITE variable. For examp le: # export PACKAGESITE=ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages/Lates t/ # or ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages-6-stable/Latest/ FreeBSD ports The port tree /usr/ports/ is a collection of software ready to compile and insta ll (see man ports). The ports are updated with the program portsnap. # portsnap fetch extract # Create the tree when running the first ti me # portsnap fetch update # Update the port tree # cd /usr/ports/net/rsync/ # Select the package to install # make install distclean # Install and cleanup (also see man ports) # make package # Make a binary package of this port # pkgdb -F # Fix the package registry database

Library path Due to complex dependencies and runtime linking, programs are difficult to copy to an other system or distribution. However for small programs with little depen dencies, the missing libraries can be copied over. The runtime libraries (and th e missing one) are checked with ldd and managed with ldconfig. # ldd /usr/bin/rsync # List all needed runtime libraries # ldconfig -n /path/to/libs/ # Add a path to the shared libraries direct ories # ldconfig -m /path/to/libs/ # FreeBSD # LD_LIBRARY_PATH # The variable set the link library path

Convert Media Sometimes one simply need to convert a video, audio file or document to another format. Text encoding 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 -t # 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, if the document displays well. Unix - DOS newlines Convert DOS (CR/LF) to Unix (LF) newlines and back within 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 which is usually fine a Unix shell. See also # DOS to UNIX # DOS to UNIX # UNIX to DOS

Convert Unix to DOS newlines within a Windows environment. Use sed or awk from m ingw or cygwin. # sed -n p unixfile.txt > dosfile.txt # awk 1 unixfile.txt > dosfile.txt # UNIX to DOS (with a cygwin shell) PDF to Jpeg and concatenate PDF files Convert a PDF document with gs (GhostScript) to jpeg (or png) images for each pa ge. Also much shorter with convert and mogrify (from ImageMagick or GraphicsMagi ck). # 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 png 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 '=' Convert video 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 an audio cd The program cdparanoia can save the audio tracks (FreeBSD port in audio/cdparano ia/), oggenc can encode in Ogg Vorbis format, lame converts to mp3. # cdparanoia -B # Copy the tracks to wav files in current d ir # 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 Print with lpr # 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=DuplexNoTumble ... # lpq # lpq -l -Php4500 # lprm # lprm -Php4500 3186 # lpc status # lpc status hp4500 th # # # # # # Check the queue on default printer Queue on printer hp4500 with verbose 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 leng

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 p rint command instead of lpr. # gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=/path/fi le.pdf Databases PostgreSQL Change root or a username password # psql -d template1 -U pgsql > alter user pgsql with password 'pgsql_password'; # Use username instead of "p gsql" Create user and 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 # -P will ask for password # createdb -U pgsql -O bob bobdb # new bobdb is owned by bob # dropdb bobdb # Delete database bobdb # dropuser bob # Delete user bob The general database authentication mechanism is configured in pg_hba.conf

Grant remote access The file $PGSQL_DATA_D/postgresql.conf specifies the address to bind to. Typical ly 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 restore The backups and restore are done with the user pgsql or postgres. Backup and res tore 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 w hen reloading an empty cluster. MySQL Change mysql root or username password Method 1 # /etc/init.d/mysql stop or # killall mysqld # mysqld --skip-grant-tables # mysqladmin -u root password 'newpasswd' # /etc/init.d/mysql start Method 2 # mysql -u root mysql mysql> UPDATE USER SET PASSWORD=PASSWORD("newpassword") where user='root'; mysql> FLUSH PRIVILEGES; # Use username instead of "ro ot" mysql> quit Create user and database (see MySQL doc) # 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 localhost instea d of % # to restrict the network acc ess mysql> DROP DATABASE bobdb; # Delete database mysql> DROP USER bob; # Delete user mysql> DELETE FROM mysql.user WHERE user='bob and host='hostname'; # Alt. comman d mysql> FLUSH PRIVILEGES; Grant remote 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 comment 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; access

# Use 'hostname' or also '%' for full

Backup and restore 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 prom pt. SQLite SQLite is a small powerful self-contained, serverless, zero-configuration SQL da tabase. Dump and restore It can be useful to dump and restore an SQLite database. For example you can edi t the dump file to change a column attribute or type and then restore the databa se. This is easier than messing with SQL commands. Use the command sqlite3 for a 3.x database. # sqlite database.db .dump > dump.sql # dump # sqlite database.db < dump.sql # restore Convert 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. Linux setup The quota tools package usually needs to be installed, it contains the command l ine 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 rw,acl,user_xattr,usrquota 1 1 # mount -o remount /home # mount # Check if usrquota is active, otherwise re boot Initialize the quota.user file with quotacheck. # quotacheck -vum /home # chmod 644 /home/aquota.user # To let the users check their own quota Activate the quota either with the provided script (e.g. /etc/init.d/quotad on S uSE) or with quotaon: quotaon -vu /home Check that the quota is active with: quota -v FreeBSD setup 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 As with Linux, add the quota to the fstab options (userquota, not usrquota): /dev/ad0s1d /home ufs rw,noatime,userquota 2 2 # mount /home # To remount the partition Enable disk quotas in /etc/rc.conf and start the quota. # grep quotas /etc/rc.conf enable_quotas="YES" # turn on quotas on startup (or NO). check_quotas="YES" # Check quotas on startup (or NO). # /etc/rc.d/quota start Assign quota limits The quotas are not limited per default (set to 0). The limits are set with edquo ta for single users. A quota can be also duplicated to many users. The file stru cture is different between the quota implementations, but the principle is the s ame: the values of blocks and inodes can be limited. Only change the values of s oft and hard. If not specified, the blocks are 1k. The grace period is set with edquota -t. For example: # edquota -u colin Linux Disk quotas for user colin (uid 1007): Filesystem blocks soft hard inodes soft hard /dev/sda8 108 1000 2000 1 0 0 FreeBSD Quotas for user colin: /home: kbytes in use: 504184, limits (soft = 700000, hard = 800000) inodes in use: 1792, limits (soft = 0, hard = 0) For many users 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 # Check quota for a user # repquota /home # Full report for the partition for all use rs

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: 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 ctrl-tab. bash Redirects and pipes for bash and sh: # cmd 1> file # Redirect stdout to file. # cmd 2> file # Redirect stderr to file. # cmd 1>> file # Redirect and append stdout to file. # cmd &> file # Redirect both stdout and stderr to file. # cmd >file 2>&1 # Redirects stderr to stdout and then to f ile. # cmd1 | cmd2 # pipe stdout to cmd2 # cmd1 2>&1 | cmd2 # pipe stdout and stderr to cmd2 Modify your configuration in ~/.bashrc (it can also be ~/.bash_profile). The fol lowing 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 indicator (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 tcsh Redirects and pipes for tcsh and csh (simple > and >> are the same as sh): # cmd >& file # Redirect both stdout and stderr to file. # cmd >>& file # Append both stdout and stderr to file. # cmd1 | cmd2 # pipe stdout to cmd2 # cmd1 |& cmd2 # pipe stdout and stderr to cmd2 The settings for csh/tcsh are set in ~/.cshrc, reload with "source .cshrc". Exam ples: # 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 promp

t 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 The emacs mode enables to use the emacs keys shortcuts to modify the command pro mpt line. This is extremely useful (not only for emacs users). The most used com mands are: 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 writ ten in this language are (quite) portable; man 1 sh is a good reference. Basics Variables and arguments Assign with variable=value and get content with $variable MESSAGE="Hello World" # Assign a string PI=3.1415 # Assign a decimal number N=8 TWON=`expr $N * 2` # Arithmetic expression (only integ ers) TWON=$(($N * 2)) # Other syntax TWOPI=`echo "$PI * 2" | bc -l` # Use bc for floating point operati ons ZERO=`echo "c($PI/4)-sqrt(2)/2" | bc -l` The command line arguments are $0, $1, $2, ... $# $* Special Variables $$ $? command if [ $? != 0 ]; then echo "command failed" fi mypath=`pwd` mypath=${mypath}/file.txt echo ${mypath##*/} echo ${mypath%%.*} var2=${var:=string} # $0 is the command itself # The number of arguments # All arguments (also $@) # The current process ID # exit status of last command

# Display the filename only # Full path without extention # Use var if set, otherwise use str

ing # 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 ion } myfunction "txt" Generate 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 Bourne script example As a small example, the script used to create a PDF booklet from this xhtml docu ment: #!/bin/sh # This script creates a book in pdf format ready to print 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 # $1 is first argument of the funct

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.bo ok.ps ps2pdf13 -sPAPERSIZE=a4 -sAutoRotatePages=None $fname.book.ps $fname.book.pdf # use #a4 and #None on Windows! exit 0 # exit 0 means successful

Some awk commands Awk is useful for field stripping, like cut in a more powerful way. Search this document for other examples. See for example gnulamp.com and one-liners for awk for some nice examples. awk '{ print $2, $1 }' file # Print and inverse first two colum ns awk '{printf("%5d : %s\n", NR,$0)}' file # Add line number left aligned awk '{print FNR "\t" $0}' files # Add line number right aligned awk NF test.txt # remove blank lines (same as grep '.') awk 'length > 80' # print line longer than 80 char) Some sed commands Here is the one liner gold mine. And a good introduction and tutorial to sed. sed 's/string1/string2/g' # Replace string1 with string2 sed -i 's/wroong/wrong/g' *.txt # Replace a recurring word with g sed 's/\(.*\)1/\12/g' # Modify anystring1 to anystring2 sed '//,/<\/p>/d' t.xhtml # Delete lines that start with # and end with sed '/ *#/d; /^ *$/d' sed 's/[ \t]*$//' s \t) sed 's/^[ \t]*//;s/[ \t]*$//' s sed 's/[^*]/[&]/' t]op sed = file | sed 'N;s/\n/\t/' > file.num # Remove comments and blank lines # Remove trailing spaces (use tab a # Remove leading and trailing space # Enclose first char with [] top->[ # Number lines on a file

Regular Expressions Some basic regular expression useful for sed too. See Basic Regex Syntax for a g ood primer. [\^$.|?*+() # special characters any other will match t hemselves \ # escapes special characters and treat as l iteral * # repeat the previous item zero or more tim es . # single character except line break charac ters .* # 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 li ne/string ^ $ # match line with a single space [^A-Z] # match any line beginning with any char fr om A to Z Some useful commands The following commands are useful to include in a script or as one liners. sort -t. -k1,1n -k2,2n -k3,3n -k4,4n # Sort IPv4 ip addresses echo 'Test' | tr '[:lower:]' '[:upper:]' # Case conversion echo foo.bar | cut -d . -f 1 # Returns foo PID=$(ps | grep script.sh | grep bin | awk '{print $1}') # PID of a running s cript PID=$(ps axww | grep [p]ing | awk '{print $1}') # PID of ping (w/o g

rep pid) IP=$(ifconfig $INTERFACE IP=$(ifconfig $INTERFACE if [ `diff file1 file2 | cat /etc/master.passwd | passwd '{ printf("%s:%s\n", $1,

| sed '/.*inet | sed '/.*inet wc -l` != 0 ]; grep -v root |

addr:/!d;s///;s/ .*//') # Linux /!d;s///;s/ .*//') # FreeBSD then [...] fi # File changed? grep -v \*: | awk -F":" \ # Create http

$2) }' > /usr/local/etc/apache2/passwd

testuser=$(cat /usr/local/etc/apache2/passwd | grep -v \ # Check user in pass wd root | grep -v \*: | awk -F":" '{ printf("%s\n", $1) }' | grep ^user$) :(){ :|:& };: # bash fork bomb. Will kill your ma chine 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 a lso 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.2008 0401 # 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 basics 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); C example A minimal c program simple.c: #include main() { int number=42; printf("The answer is %i\n", number); } Compile with: # gcc simple.c -o simple # ./simple The answer is 42 C++ basics *pointer &obj obj.x pobj->x j

/* /* /* /*

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 ints */ /* Convert in i to char str */

// // // //

Object pointed to Address of object Member x of class Member x of class

by pointer obj obj (object obj) pointed to by pob

// (*pobj).x and pobj->x are the same

C++ example 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. IPv4 class IPv4.h: #ifndef IPV4_H #define IPV4_H #include 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 #include using namespace std; using namespace GenericUtils;

// use the namespaces

IPv4::IPv4() {} // default constructor/destruc tor IPv4::~IPv4() {} string IPv4::IPint_to_IPquad(unsigned long ip) { // member implementation ostringstream ipstr; // use a stringstream ipstr << ((ip &0xff000000) >> 24) // Bitwise right shift << "." << ((ip &0x00ff0000) >> 16) << "." << ((ip &0x0000ff00) >> 8) << "." << ((ip &0x000000ff)); return ipstr.str(); } The program simplecpp.cpp #include "IPv4.h" #include #include using namespace std; int main (int argc, char* argv[]) { string ipstr; unsigned long ipint = 1347861486; GenericUtils::IPv4 iputils; ss ipstr = iputils.IPint_to_IPquad(ipint); cout << ipint << " = " << ipstr << endl; return 0; } Compile and execute with: # g++ -c IPv4.cpp simplecpp.cpp # g++ IPv4.o simplecpp.o -o simplecpp.exe table

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

# Compile in objects # Link the objects to final execu

# ./simplecpp.exe 1347861486 = 80.86.187.238 Use ldd to check which libraries are used by the executable and where they are l ocated. Also used to check if a shared library is missing or if the executable i s static. # ldd /sbin/ifconfig # list dynamic object dependencie s # ar rcs staticlib.a *.o # create static archive # ar t staticlib.a # print the objects list from the archive # ar x /usr/lib/libc.a version.o # extract an object file from the archive # nm version.o # show function members provided by object Simple Makefile 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 Documentation Linux Documentation 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 FreeBSD user wiki www.freebsdwiki.net Solaris Man Pages docs.sun.com/app/docs/coll/40.10 Other Unix/Linux references Rosetta Stone for Unix bhami.com/rosetta.html (a Unix command translator) Unix guide cross reference unixguide.net/unixguide.shtml Linux commands line list www.linuxcmd.org Short Linux reference www.pixelbeat.org/cmdline.html Little command line goodies www.shell-fu.org

That's all folks!

Potrebbero piacerti anche