quarta-feira, 24 de dezembro de 2008

Convert VMware image to VirtualBox

Install qemu.

$ vmware-vdiskmanager -r Slackware.vmdk -t 0 /tmp/vmware_image.vmdk

$ qemu-img convert /tmp/vmware_image.vmdk /tmp/vbox_image.bin

$ VBoxManage convertdd /tmp/vbox_image.bin Slackware.vdi

Referência: www.cyberciti.biz/tips/converting-from-vmware-images-to-virtualbox-images.html

quinta-feira, 4 de dezembro de 2008

F380 shared via XP

Tenho uma impressora HP Desjet F380 instalada em uma maquina com Windows XP. Ela foi compartilhada pelo Windows XP de modo que um cliente via Samba em uma maquina com Ubuntu Linux e outras maquinas com Windows pudessem utilizar esta impressora.

Instalada a impressora no Ubuntu via Samba, ao efetuar um teste, ocorria alguma falha de comunicacao de modo que nenhum trabalho enviado pela maquina com Ubuntu fosse impresso.

Se voce tiver um problema parecido com esse ou outros modelos de impressora, basta desativar o suporte Bidirecional da impressora na maquina Windows.

sexta-feira, 19 de setembro de 2008

Sort by field

/tmp/input:

192.168.1.100
192.168.1.19
192.168.1.102
192.168.2.1
192.168.0.2

# sort -t . -k 3,3n -k 4,4n /tmp/input

-t . : Set field to . (dot) as our IPs separated by dot symbol
-n : Makes the program sort according to numerical value
-k opts: Sort data / fields using the given column number. For example, the option -k 2 made the program sort using the second column of data. The option -k 3,3n -k 4,4n sorts each column. First it will sort 3rd column and then 4th column.

Output:

192.168.0.2
192.168.1.19
192.168.1.100
192.168.1.102
192.168.2.1

Referência

quarta-feira, 10 de setembro de 2008

Summer 2008

# cat << EOF > /usr/share/zoneinfo/Brazil/summer2008.zic
Rule Brazil 2008 only - Oct 19 00:00 1 S
Rule Brazil 2009 only - Feb 15 00:00 0 -

Zone Brazil/East -3:00 Brazil BR%sT
EOF

# zic /usr/share/zoneinfo/Brazil/summer2008.zic

# cat /etc/localtime > /etc/localtime.copy && \
ln -s /usr/share/zoneinfo/Brazil/East /etc/localtime

XFS

# mkfs.xfs -d agcount=4 -l size=32m /dev/[DEVICE]

Mount options: noatime,nodiratime,logbufs=8

Check fragmentation factor:

# xfs_db -r /dev/[DEVICE]

# xfs_db> frag & hit enter

If you need to defrag your hard drive:

# xfs_fsr -v /dev/[DEVICE]

terça-feira, 2 de setembro de 2008

ext3 tuning

1) Directory indexing

# tune2fs -O dir_index /dev/hdXY
# e2fsck -D /dev/hdXY

2) Journal mode

# tune2fs -O has_journal -o journal_data /dev/hdXY

3) Mount options

# mount -o nodiratime,noatime,data=journal /dev/hdXY /your_mount_point

Referências:

Advanced filesystem implementor's guide, Part 8

Ext3 tuning

terça-feira, 29 de julho de 2008

How to flash BIOS

wget http://www.fdos.org/bootdisks/autogen/FDOEM.144.gz
gunzip FDOEM.144.gz
mount -t vfat -o loop FDOEM.144 /mnt/temp
cp 1400_A09.EXE /mnt/temp (Dell Vostro 1400 BIOS A.09)
umount /mnt/temp
mkisofs -o bootable_freedos.iso -b FDOEM.144 FDOEM.144
cdrecord -v dev=0,0,0 speed=4 -eject bootable_freedos.iso

sexta-feira, 18 de julho de 2008

Java: Fix JDK6 on Xorg

Locking assertion failure. Example: Linux + JDK6 + Netbeans.

Try this as root:

export LIBXCB_ALLOW_SLOPPY_LOCK=true

Or this:

sed -i 's/XINERAMA/FAKEEXTN/g' /opt/java/jre/lib/i386/xawt/libmawt.so

Or:

export LIBXCB_ALLOW_SLOPPY_LOCK=1

Shell: external variable in awk

awk -v x=0 'NF != 6 { ++x } END { print x, NR }' out.lst

This time we're passing awk an external variable. When you do this you have to tell awk what you're doing be prefixing the variable with -v. So we've initialized x to be equal to zero before actually starting our awk program.

Shell: Killing child processes from a pid


for child in $(ps -o pid,ppid -ax | \
awk "{ if ( \$2 == $pid ) { print \$1 }}")
do
echo "Killing child process $child because ppid = $pid"
kill $child
done

Shell: Length of a string

$ expr length "nixcraft"
8

$ myVar="nixcraft"
$ echo ${#myVar}
8

$ echo nixcraft | awk ‘ { print length } ‘
8

$ echo nixcraft | perl -nle ‘ print length ‘
8

Linux: Optimize Directories ( File Access Time ) in ext3 Filesystem

Linux: wget ignores robot.txt entry

on the command line: -erobots=off

http://cygwin.com/ml/cygwin/2003-02/msg00944.html

Linux: How to Tunnel X Windows Securely over SSH

Linux: Disk Cloning

Serve the disk image:

$ dd if=/dev/hda | nc -l -p port

Receive the image:

$ nc -w3 hostname port | dd of=/dev/hda

OR

On the receiving end do:

$ netcat -l -p 7000 | tar x

And on the sending end do:

$ tar cf - * | netcat otherhost 7000

Linux: Dividindo arquivos tar em múltiplos volumes

$ tar -c -M --tape-length=700000 --file=cd1.tar arquivao.tar.gz

Onde a opção "--tape-length" é multiplicada por 1024 bytes (por arredondamento: 700000 x 1024 = +- 700Mb)

Quando o primeiro arquivo chegar a 700mb, o tar dará o seguinte prompt:

Prepare volume #2 for cd1.tar and hit return:

Para começar a escrever no segundo arquivo, digite:

$ n cd2.tar

Caso você saiba previamente quantos volumes o arquivo irá gerar, o seguinte comando não precisará de interação:

$ tar -c --tape-length=700000 -f cd1.tar -f cd2.tar arquivao.tar.gz

A opção "--tape-length" também pode ser substituída por "-L"

Para restaurar o arquivo:

$ tar -x -M --file=cd1.tar --file=cd2.tar arquivao.tgz

Linux: Getting SSH daemon to start

Getting SSHD to start involved fixing this error:

$ fatal: daemon() failed: No such device

which was fixed by deleting the FILE:

$ /dev/null

that yum or something had created, and then running the command:

$ mknod /dev/null c 1 3

Once that was done, SSHD started up OK again.

Problema: Acentuacao+Java+Linux

http://my.opera.com/CrazyTerabyte/blog/2007/02/02/poor-interface-design

Recuperando partições e corrigindo sistemas de arquivos

http://www.guiadohardware.net/tutoriais/recuperando-particoes-corrigindo-sistemas-arquivos/

Answering Novice Shell Questions

http://www.samag.com/documents/s=10118/sam0703g/0703g.htm

Parallelize applications for faster Linux booting

http://www-128.ibm.com/developerworks/linux/library/l-boot-faster/index.html?ca=drs-

Shell: Cutting last line

tac teste.txt | awk 'NR > 1' | tac

Shell: Inserir uma linha no inicio de arquivo

(echo "hoge"; cat hoge.txt)

insege hoge no inicio do arquivo hoge.txt

How to display or show information about a Linux Kernel module or drivers

http://www.cyberciti.biz/tips/how-to-display-or-show-information-about-a-linux-kernel-module-or-drivers.html

Host multiple SSL sites on a single network card with IP aliasing

http://www-128.ibm.com/developerworks/library/wa-multissl.html?ca=drs-

Usando screen

# .profile (Usuario)
# Adicionar a seguinte linha:
screen -d -R

# .screerc (Usuario)
# Adicionar as seguintes linhas:
multiuser on
acladd root

# Para acessar o screen:
screen -r Usuario/

sudo FAQ

http://polishlinux.org/first-steps/root-account/sudo-faq/

How to install SystemRescueCd on an USB-stick

http://www.sysresccd.org/Sysresccd-manual-en_How_to_install_SystemRescueCd_on_an_USB-stick

Replacing A Failed Hard Drive In A Software RAID1 Array

http://www.howtoforge.com/replacing_hard_disks_in_a_raid1_array

Para criar um arquivo morto

dd if=/dev/zero of=10.smk bs=1024 count=$N

onde $N*1024=tamanho em bytes do arquivo necessario.
Use echo 0 >> 10.smk para acrescentar 2 bytes no arquivo.

Format MBR

dd if=/dev/zero of=/dev/hda bs=446 count=1

Copying mass amounts of data over a network with bash, rsync

rsync -ave ssh srcpath user@host:/dstpath

or you could even tar over ssh for super-fast synching and no file list delay by doing a:

tar -cf - /srcpath | ssh -c blowfish-cbc user@host '(cd /dstpath; tar xf -)'

Ref: http://corneliusroot.blogspot.com/2006/12/copying-mass-amounts-of-data-over.html

Zerando a senha da BIOS

# printf "\x2E" | dd bs=1 seek=112 of=/dev/port
# printf "\xFF" | dd bs=1 seek=113 of=/dev/port

O "printf" converte o texto em hexadecimal no byte correspondente e repassa este byte para o comando dd que por sua vez escreve este byte na porta 0x70 (112) e 0x71(113).

Ref: http://linuxabordo.com.br/blog/jonnyzone.php?title=zerando_resetando_a_bios_pela_linha_de_c

Accelerating OpenSSH connections with ControlMaster

Add this lines to ~/.ssh/config:


Host *
ControlMaster auto
ControlPath ~/.ssh/master-%r@%h:%p


Referência: http://www.linux.com/articles/54498

Shell Obfuscator

http://comp.eonworks.com/scripts/obfsh

quinta-feira, 29 de maio de 2008

Linux: Como alternar facilmente o mapa de teclados no X

Estou com um notebook cujo teclado é ABNT2. Eu pessoalmente não gosto desse layout e sempre que possível utilizo um teclado com layout internacional na porta USB dessa máquina. Para facilitar essa troca de mapeamento, fiz a seguinte configuração no meu /etc/X11/xorg.conf:


Section "InputDevice"
Identifier "Keyboard0"
Driver "kbd"
Option "XkbRules" "xorg"
Option "XkbModel" "abnt2"
Option "XkbLayout" "us"
Option "XkbOptions" "grp:switch,grp:lwin_toggle"
Option "XkbVariant" "alt-intl"
EndSection


Ou seja, vou utilizar o famigerado botão left win para efetuar a troca do mapeamento.

quarta-feira, 23 de abril de 2008

Dica Postgres - Obter quantidade de linhas de update no PL/pgsql

Para obtermos no PostgreSQL o número de linhas atualizadas por um UPDATE por exemplo, devemos usar a opção GET DIAGNOSTICS. Veja o exemplo na sequência:

CREATE OR REPLACE FUNCTION f_insert_pesq(
         p_dn_simulation_number integer, 
         p_dc_protocol character varying, 
         p_dn_scenario integer, 
         p_dn_variation integer, 
         p_dn_subscenario integer, 
         p_dn_pesq double precision
) RETURNS character varying AS
$BODY$
DECLARE
    v_count INTEGER;
BEGIN
 UPDATE simulation SET dn_pesq = p_dn_pesq
 WHERE dn_simulation_number = p_dn_simulation_number
 AND dc_protocol = p_dc_protocol
 AND dn_scenario = p_dn_scenario
 AND dn_variation = p_dn_variation
 AND dn_subscenario = p_dn_subscenario;

 GET DIAGNOSTICS v_count = ROW_COUNT;

 IF v_count > 0 THEN
         RETURN 'success update';
 ELSE
  RETURN 'simulation not found';
 END IF;
END;
$BODY$
LANGUAGE 'plpgsql';


Tranquilis em !!!

sexta-feira, 18 de abril de 2008

Shell: timestamp2datetime

php -r "print date('l dS \of F Y h:i:s A', $1) . \"\n\";"

Shell: Script para retornar timestamp de um arquivo


#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 file"
exit
fi
echo $1 | \
cpio -o 2> /dev/null | \
od -x | \
sed -n 'n;s/[^ ]* *\(....\) *\(....\).*/16i\1\2p/;y/abcdef/ABCDEF/;p;q' | \
dc

Shell: Script para alterar o fundo de tela


#!/bin/bash
#
# setwallpaper.sh

BG_DIR="$HOME/wallpapers"
TOTAL=`ls -f $BG_DIR/* | grep -E ".png|.jpg" -c`
IMG=$(($RANDOM%$TOTAL))
COUNT=0
for i in `find $BG_DIR -type f | sort` ;
do
if [ $COUNT -eq $IMG ];
then
rm "$BG_DIR/background"
ln -s "$i" "$BG_DIR"/background
xv -viewonly -rmode 5 -rbg black -root -quit -maxpect $BG_DIR/background
exit
fi
COUNT=$(($COUNT+1))
done

Shell: Script para gerar screenshots


#!/bin/bash
#
# snapshot.sh
DATE=`date +%d%m%Y-%H%M%S`
xwd -root | convert - "$HOME/snapshot-$DATE.jpg"

Linux: xbindkeys

Xbindkeys é um programa que permite mapear teclas de atalho para execução de programas. Muito útil para mim que uso gerenciadores de janela que não fazem o mapeamento de teclas especias do meu notebook.

Para efetuar um mapeamento, execute-o com o parâmetro -k. Desse modo, ele executa em modo de "escuta" retornando uma sequência de instruções as quais você insere no arquivo .xbindkeysrc no seu HOME.

Logo abaixo, o arquivo de configuração que utilizo na minha máquina:

"amixer set Master 3%+"
m:0x0 + c:176
NoSymbol

"amixer set Master 3%-"
m:0x0 + c:174
NoSymbol

"amixer set Master toggle"
m:0x0 + c:160
NoSymbol

"xlock"
m:0x40 + c:72
Mod4 + F6

"music_control.sh --stop"
m:0x0 + c:164
NoSymbol

"music_control.sh --fwd"
m:0x0 + c:153
NoSymbol

"music_control.sh --play-pause"
m:0x0 + c:162
NoSymbol

"music_control.sh --rew"
m:0x0 + c:144
NoSymbol

Shell: Script genérico para controle de players de som



#!/bin/bash
#
# music_control.sh

unset PROGRAM
unset PLAYERS

PLAYERS="xmms.bin amarok audacious"

for PROGRAM in $PLAYERS ;
do
if ps -u $USER | grep $PROGRAM > /dev/null 2>&1 ;
then
break
else
unset PROGRAM
fi
done

[ -z $PROGRAM ] && exit 1

case "$1" in
'--play-pause')
$PROGRAM -t
;;
'--stop')
$PROGRAM -s
;;
'--rew')
$PROGRAM -r
;;
'--fwd')
$PROGRAM -f
;;
*)
echo "Usage: $0 --play-pause | --stop | --rew | --fwd"
exit 1
;;
esac

quinta-feira, 17 de abril de 2008

Linux: xtermcontrol

Meu terminal padrão é o xterm. Como uso ele ou no Wmii ou Awesome, ás vezes tenho o incoveniente de estar logado em várias máquinas ao mesmo tempo e não saber em qual terminal é cada máquina. Uma forma de resolver foi com o uso do programa xtermcontrol. Utilizo esse programa da seguinte maneira:

# .bashrc

vim () {
command vim $*
xtermcontrol --title $USER@$HOSTNAME
}

ssh () {
for i in $*; do
if [ `echo $i | grep -E "@|\.|i\d*"` ]; then
xtermcontrol --title $i
fi
done
command ssh $*
xtermcontrol --title $USER@$HOSTNAME
}


Como vocês podem ver criei sub-rotinas para rodar o vim e o ssh. Dessa forma, quando estou logado em uma máquina, o título do xterm apresenta o endereço da máquina e assim sei exatamente onde estou.

Awesome com gráficos



Depois da experiência com o wmii, o nosso amigo r3n4n descobriu mais um window manager pequeno, completo e de fácil manipulação, o awesome.

Além de todas as suas facilidades, o awesome tem configurações interessantes de objetos para gráficos e barras de progresso.

Através do meu já modificado e antigo script de status do wmii, consegui integrar as informações obtidas a essas funcionalidades.


O script de status pode ser obtido no link script de status awesome em conjunto ao script de configuração do awesome que está no link awesomerc.

quarta-feira, 16 de abril de 2008

Convertendo videos para o formato 3gp (celular)

Inicialmente vamos reduzir o vídeo e transforma-lo em avi

mencoder SEU_VIDEO -nosound -ovc lavc -lavcopts vcodec=mpeg4 -vf expand=128:96,scale=128:96 -o movie.avi -ofps 12

Para que o video tenha melhor resolução, você pode utilizar 176:144 na escala e expansão

Bom, temos agora que obter o som do video
mplayer -vo null -ao pcm -af resample=8000,volume=+4db:sc SEU_VIDEO

Na sequência vamos unir o som e o video reduzido ao formato 3gp
ffmpeg -i movie.avi -i audiodump.wav -b 48 -ac 1 -ab 12 -map 0.0 -map 1.0 undo.3gp

Referências:

segunda-feira, 14 de abril de 2008

Linux: Como alterar o modo de operação de uma interface de rede

# /sbin/mii-tool -F 100baseTx-FD eth0

Força a eth0 trabalhar em 100mbits Full Duplex. Os possíveis modos são:

100baseTx-FD, 100baseTx-HD, 10baseT-FD ou 10baseT-HD.

Drunk Penguins

Drunk Penguins
Drunk Penguins