Tuesday, September 28, 2010

VMware Mouse Grab Problem

Some time ago I instaled vmware server in my machine and the mouse was just going crazy, just move it a little and lose focus from the VM Console.


This seems to be due to some changes in the new versions of GTK, so to correct that do the following:


Go to the extension directory



~/.mozilla/firefox/.default/extensions/VMwareVMRC@vmware.com/plugins/lib/wrapper-gtk24.sh


and add in the second line:


export VMWARE_USE_SHIPPED_GTK=yes


And that's it! Just restart Firefox and it works! 


I got this solution from here: http://www.linuxinsight.com/vmware-mouse-grab-ungrab-problem.html

Monday, September 20, 2010

Utilizando o Installwatch

E aqui vai outra do Dicas-L:

http://www.dicas-l.com.br/arquivo/utilizando_o_installwatch.php
Para quem usa Slackware, Debian ou RedHat um ótimo software para se usar na hora de instalar programas a partir do código fonte é o checkinstall, ele gera um pacote com o software sendo compilado para que depois possa ser instalado/desinstalado com facilidade,
A maior utilidade desse software para mim é a facilidade de desinstalação.
Porém agora estou utilizando o gentoo, pois foi a melhor distro que encontrei para 64 bits.
Por causa disso descobri que o checkinstall é baseado em um outro software chamado installwatch, que faz toda a parte de gerenciamento dos arquivos que estão sendo instalados.
Depois de muito tempo procurando pelo installwatch pela internet eu descobri que ele se encontra no próprio fonte do checkinstall,
Então para se instalar façamos o seguinte:
Baixe o checkinstall: http://asic-linux.com.mx/~izto/checkinstall/ E faça o seguinte:

$ tar xvfz checkinstall-1.6.0.tgz
  $ cd checkinstall-1.6.0/installwatch-0.7.0beta4/
  $ make
  # make install

Agora crie os diretórios onde teremos informações dos pacotes instalados e removidos:

# mkdir /var/{install,uninstall}

E pronto, agora sempre que compilar um pacote, ao invés de utilizar o famoso "make install", use:

# installwatch -o /var/install/<NOME_DO_SOFTWARE> make install

Será criado um arquivo em /var/install com o nome do software instalado e informação de todos arquivos criados,
Para facilitar o processo de instalação pode-se criar um alias:

# alias iw='installwatch -o /var/install/$(basename $(pwd))'

A linha acima pode ser adicionada ao arquivo /etc/profile, para que tenhamos esse alias sempre que iniciarmos uma sessão, apenas note que o nome do arquivo que ficará no diretório/var/install é o nome do diretório onde você se encontra, tome os devidos cuidados para não estar num diretório com o nome incorreto ou com o nome que pode sobrescrever a informação de outro pacote previamente instalado, particularmente eu tive apenas esse "problema" quando compilando pacotes cvs que tinham o diretório "trunk".
E ao invés de digitar toda a enorme linha acima para se instalar o pacote é só utilizar:

# iw make install

Para se desinstalar podemos utilizar o script nuke da seguinte forma:

# nuke /var/install/<NOME_DO_SOFTWARE>

Abaixo segue o script nuke:

#!/usr/bin/perl
  # Author: Robert Park <feztaa@shaw.ca>
  # License: GNU General Public License
  
  # Revision 1.13  2002/08/08 00:51:34  feztaa
  # Added experimental --package and --install options for tarring up
  # and untarring packages from installwatch logfiles.
  #
  # Revision 1.12  2002/07/31 07:11:43  feztaa
  # Fixed major problem with symlinks that point to directories.
  #
  # Revision 1.11  2002/07/27 00:45:39  feztaa
  # Major overhaul; reduced LOC and increased efficiency all around.
  #
  # Revision 1.10  2002/07/26 19:41:00  feztaa
  # Incorporated fixes from Zenith Lau <zenithlau@sniic.com>, fixing
  # issues with symlinks.
  
  use strict;
  
  die "You must be root!\n" unless ($< == 0);
  
  # Underline a string by appending with with a newline and hyphens
  sub underline
  {
   my $str = join("", @_);
   my $chomp = 1;
  
   $chomp++ while (chomp $str);
  
   return "$str\n" . ("-" x length $str) . ("\n" x $chomp);
  }
  
  # Take an array, and return a string that's been properly commified,
  # ie ("one", "two", "three") becomes "one, two, and three".
  sub commify
  {
   (@_ == 0) ? ''                                      :
   (@_ == 1) ? $_[0]                                   :
   (@_ == 2) ? join(" and ", @_)                       :
               join(", ", @_[0 .. ($#_-1)], "and $_[-1]");
  }
  
  my %opts;
  my @args;
  
  foreach my $arg (@ARGV)
  {
   ($arg =~ m/^(-r|--report)$/) ?  $opts{report}  = 1 :
   ($arg =~ m/^(-p|--package)$/) ? $opts{package} = 1 :
   ($arg =~ m/^(-i|--install)$/) ? $opts{install} = 1 :
                                   push @args, $arg;
  }
  
  # Process all the logfiles
  foreach my $arg (@args)
  {
   $arg =~ s#^.*/##g;
   chomp $arg;
  
   my $install = "/var/install/" . $arg;
   my $package = "/var/packages/" . $arg . ($opts{install} ? "" : ".tar.bz2");
   my $uninstall = "/var/uninstall/" . $arg;
  
   unless ((-f $install and not $opts{install}) or (-f $package and $opts{install}))
   {
     print "Can't find $arg\n";
     next;
   }
  
   if ($opts{install})
   {
     print "Unpacking files from $package ... \n";
     system("tar", "-Pxjvpf", $package);
   }
   else
   {
     open "INSTALL", "<$install" or die "$!\n";
  
     print "Processing $arg ... ";
  
     my %files;
     my $error = 0;
  
     while (<INSTALL>)
     {
       chomp;
       my @fields = split;
  
       my $action = $fields[1];
       my $file = $action eq "symlink" ? $fields[3] : $fields[2];
  
       # Don't delete stuff that wasn't created properly;
       # prevents deletion of /usr or similar.
       if ($fields[-1] eq "#success")
       {
         push @{ $files{$file} }, $action if (-f $file or -l $file or -d $file);
       }
     }
  
     print "done.\n";
  
     if ($opts{report})
     {
       # Reporting mode, don't delete anything.
       print underline("Files/Directories installed by $arg\n");
  
       foreach my $file (sort { length $b <=> length $a } keys %files)
       {
         print "$file:  ", commify (@{ $files{$file} }), "\n";
       }
     }
     elsif ($opts{package})
     {
       print "Packing files from $arg into $package ... \n";
  
       system("tar", "-cpPvjf", $package, (sort keys %files), $install);
     }
     else
     {
       # Nuke mode, delete stuff...
       print "Uninstalling $arg ... ";
  
       open "UNINSTALL", ">$uninstall" or die "$!\n";
  
       select UNINSTALL;
  
       print underline("Removed Files/Directories");
  
       foreach my $file (sort { length $b <=> length $a } keys %files)
       {
         if (grep /open|symlink|mkdir/, @{ $files{$file} })
         {
           $! = "";
  
           print "\n$file";
  
           # -d returns true for symlinks that point to directories,
           # so this is actually necessary.
           (-l "$file") ? unlink "$file" :
           (-d "$file") ? rmdir "$file"  :
                          unlink "$file";
  
           if ($!)
           {
             print " -- $!";
             $error++;
           }
         }
       }
  
       close "INSTALL";
       close "UNINSTALL";
       select STDOUT;
  
       # Let the user know what happened
       if ($error)
       {
         print "$error files/directories could not be removed.\n";
       }
       else
       {
         unlink $install;
         print "successful.\n";
       }
     }
   }
  }

Um muito obrigado aos criadores desses softwares! Meu sistema estaria cheio de lixo sem eles!

Recuperando o Grub Perdido

Aqui vai um link de uma dica minha no Dicas-L:

http://www.dicas-l.com.br/arquivo/recuperando_o_grub_perdido.php


Quem nunca instalou um outro SO ou fez alguma besteira e perdeu o Grub (ou lilo)?
Todos seus arquivos estão lá, seu SO está do jeito que você deixou, mas você não consegue iniciar o sistema pois a MBR está incorreta.
Bom, pra resolver é bem simples.
  1. Ligue a máquina com um Live CD de sua preferência, o ideal é que seja o mais similar possível ao sistema instalado, principalmente versão de kernel;
  2. Após o boot, liste as partições existentes para descobrir quais as partições necessárias para o SO:
    # fdisk -l
      
      Disk /dev/sda: 160.0 GB, 160041885696 bytes
      255 heads, 63 sectors/track, 19457 cylinders
      Units = cylinders of 16065 * 512 = 8225280 bytes
      Disk identifier: 0x053687be
      
       Device Boot      Start         End      Blocks   Id  System
      /dev/sda1   *           1        5099    40957686    7  HPFS/NTFS
      /dev/sda2            5100       19457   115330635    5  Extended
      /dev/sda5            5100        7649    20482843+   b  W95 FAT32
      /dev/sda6            7650       10199    20482843+   7  HPFS/NTFS
      /dev/sda7           10200       12749    20482843+   b  W95 FAT32
      /dev/sda8           12750       12762      104391   83  Linux
      /dev/sda9           12763       16586    30716248+  83  Linux
      /dev/sda10          16587       19391    22531131   83  Linux
      /dev/sda11          19392       19457      530113+  82  Linux swap / Solaris
    
  3. Crie um mount point e monte sua partição de root:
    # mkdir /mnt/recover
      # mount /dev/sda10 /mnt/recover
    
    Caso você não saiba qual é sua partição de root, monte partição por partição até encontrar, o conteúdo da raiz não será muito diferente disso:
    # ls -1 /
      bin
      boot
      cdrom
      dev
      emul
      etc
      home
      initrd.img
      initrd.img.old
      lib
      lib32
      lib64
      media
      mnt
      opt
      proc
      root
      sbin
      selinux
      srv
      sys
      tmp
      usr
      var
      vmlinuz
      vmlinuz.old
    
  4. Verifique no seu /etc/fstab  quais outras partições de sistema existem, se existir elas precisam ser montadas, em geral o que pode ser necessário é:
    /opt
      /tmp
      /usr
      /var
      /boot
    
    Caso seu /etc/fstab mostre o UUID do disco ao invés do dispositivo, você pode descobrir qual é o dispositivo com o comando blkid:
    # blkid /dev/sda10
      /dev/sda10: LABEL="linux" UUID="57c5cf37-4a13-4a85-a088-716e758e6a0b" TYPE="xfs"
    
  5. Monte todas as partições necessárias no seu local correto, por exemplo, para montar a partição/usr, após verificar que ela está presente na partição sda8:
    # mount /dev/sda8 /mnt/recover/usr
    
  6. Certifique-se de que todas as partições necessárias estão montadas, principalmente a partição/boot.
  7. Monte os pseudo devices:
    # mount -t proc none /mnt/recover/proc
      # mount -o bind /dev /mnt/recover/dev
    
  8. Entre no ambiente
    # chroot /mnt/recover /bin/bash
    
  9. Crie o /etc/mtab
    # grep -v rootfs /proc/mounts > /etc/mtab
    
    Nesse ponto, caso você tenha muitas partições de sistema, como /usr por exemplo, é possível que seja necessário editar o arquivo e retirar o prefixo /mnt/recover.
  10. Confira se o /boot/grub/grub.conf ou /boot/grub/menu.lst ou /boot/grub/grub.cfgestá correto (o arquivo depende da versão do grub e/ou da configuração).
  11. Execute o grub-install no disco.
    # grub-install /dev/sda
    
  12. Reinicie a máquina e fique feliz!
É possível que, devido ao novo SO instalado, alguns discos mudem de ID para o grub, nesse caso, você receberá uma mensagem de que a partição não é bootável.
Nesse caso, aconselho editar a linha do grub no momento da inicialização (apertando "e") e mudando o (hdX,Y) por valores de outras partições que existem no sistema, até se encontrar qual é a partição de root correta.
Uma vez encontrada a partição correta, inicie o sistema e edite o arquivo de configuração do grub com as informações corretas.

Thursday, September 16, 2010

Connecting to Multiple Networks

Here in my job I have to connect to two networks, one the intranet of the company and other a 3G network in order to access my email (since I am not a employe I don't have a company mail, and use a free one for everything).

Since I only really need to use the company network to access the nodes I do support, the best option would be connect to both network and use the company one when I try to access the nodes, and the 3G network for everything else (which would basically mean all the internet). Before using this solution I was always needing to change from one network to another depending on what I needed to do.

So, how to do that? It is so incredible easy that took me some weeks to find out! ;)

Basically you first need to connect to both networks (one at a time), and take a look at your routing table.

Ok, so, first I connect to my company network (via cable, which in my case mean that interface eth0 will be used), and it gives me a routing table like the following (obviously, I am changing the address):
$ netstat -rn 
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         10.10.10.1   0.0.0.0         UG        0 0          0 eth0

Ok, so lets disconnect and see how it looks like when connecting to the 3G (which in my case is the ppp0 interface):

$ netstat -rn 
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         192.168.1.1   0.0.0.0         UG        0 0          0 ppp0

It can have some other lines in the configuration, but the "0.0.0.0" line (depending on the configuration it will be shown as "default").
Well, once you have the default route information, just connect to both networks, delete the default route, and add the route you want, in my case I do something like this:

route del default
route add -net 10.10.8.0/23 gw 10.10.10.1 dev eth0
route add -net 10.11.0.0/16 gw 10.10.10.1 dev eth0
route add -net 10.12.50.0/24 gw 10.10.10.1 dev eth0
route add default gw 192.168.1.1 dev ppp0

Where the first line delete the current default route, the 3 next lines add the routing to the nodes I need to have access in my work, and the other creates a default route for everything else to go through the 3G connection.

Hope it helps you people!

Wednesday, September 15, 2010

Java Plugin 64bits

As someone may have already notice I am using this blog more as a way to remind myself some little things to do when I install a new Linux than any other thing.

And here is another small but importante detail: In the newer versions of Sun Java for 64bits environments there is already a native plugin for your browser, in debian you just need to do this to be happy:

ln -s /usr/lib/jvm/java-6-sun/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/libnpjp2.so

Since /usr/lib/jvm/java-6-sun is a link to the newest java-6 version, you will only need to change the link if you want to change the java from 6.x to 7.x (which is not likely to happen frequently), otherwise even in the usual java updates you won't need to worry about anything, except maybe a Firefox / Iceweasel messages saying that some plugins have been changed and it need to be restarted.

MS Office in Linux

In the newer versions of wine is incredible easy to install the versions of MS Office prior to 2007, but after doing that I had some little trouble on how to make KDE use the MS Office Applications to correctly open a MS Office document when I click on it.

Well, the answer, as usually happens in Unixes, come as the form of a script.

Actually, two scripts for each MS Office application, on when you call it via shell and the other to be used exclusively when it is called by KDE.

Here is the one to be used by the KDE configuration, I usually place it under /usr/local/bin/winword-gui, and here are its contents:

#!/bin/bash
FILENM=$( basename "$@" )
UNXDIR=$( dirname "$@" )
WINDIR=$( echo $UNXDIR | sed 's@\/@\\@g' )
DOCPTH="Z:$WINDIR\\$FILENM"
/usr/bin/wine "C:\Program Files\Microsoft Office\Office12\WINWORD.EXE" "$DOCPTH" &

After creating this file you just right click on some .doc file in KDE and go "Open with -> Other" and select the file you created.

And, if you want to call it via shell, you can have this other script named /usr/local/bin/winword:

#!/bin/bash
/usr/bin/wine "C:\Program Files\Microsoft Office\Office12\WINWORD.EXE" "$@" &

Obviously depending on your wine configuration and office installation you need to change the last line of both scripts.

It could also be done in just one script, but since I am so lazy I prefer to just let it like this.

For the other MS Office applications, you create the same scripts but change the last line for the program you want (EXCEL.EXE, POWERPNT.EXE or whatever).

Ear phone not working in HP Pavillion

Here is what I had do add to my /etc/modprobe.d/alsa-base.conf so my ear phones start working, without it when I plugged it nothing changes, the sound keep going out only by the speakers.

Those are the magic lines:

alias snd-card-0 snd-hda-intel
alias snd-card-1 snd-usb-audio
alias sound-slot-0 snd-hda-intel
options snd-hda-intel index=0 model=hp-dv5 enable-msi=1 position-fix=1
options snd-usb-audio index=1

Peace!

Things I usually add to my bashrc

Here are some little things I usually like to add to my bash configuration, since I used debian the file is /etc/bash.bashrc, but could also be ~/.bashrc:

readonly HISTTIMEFORMAT="%d/%m/%Y at %T: "
readonly HISTFILESIZE=5000
export HISTCONTROL="erasedups"
readonly command_oriented_history=1
export HISTTIMEFORMAT HISTFILESIZE HISTCONTROL command_oriented_history
source /usr/bin/funcoeszz
shopt -s histappend
shopt -s cdspell
shopt -s dirspell
history -a
set -o vi
if [ -x /usr/games/fortune ]; then
        echo
        /usr/games/fortune -a
        echo
fi

Much funnier than default!

Monday, September 13, 2010

Backup Files Bigger than 4Gb in FAT Filesystems

Sometimes we need to copy files to Fat filesystem that are larger than 4Gb, which this filesystem do not support, if I need to do that just for some period (as backup), I use the following:

$ rar a -m0 -v500M -R <rar-file-name> <original-file>

It won't compress the file (-m0 parameter) and will divide the file into smaller 500M file (-v500M parameter).

I already used it in a lot of situations where I really needed to free some space in a more decent filesystem (usually my XFS home or root partitions).

Peace!

Backup with rsync

Millions of years after the last post I decided to make it come to live again, lets see for how long.

Simple, simple thing to start the new era, that's how I am usually making the backups from my work directory in my machine to the external disk:

rsync -av --link-dest=/Backups/2010-09-07/ ~/Work/ /Backups//2010-09-08/

This way everything that already exists in the previous backup (2010-09-10 directory) will be hard linked to the new backup, so my space is not all wasted and I can keep track of what was changed from backup to backup.

That's funny how the size is shown when you use those hard links:

$ mkdir 1 2
$ dd if=/dev/zero of=./1/somefile bs=1k count=5120
5120+0 records in
5120+0 records out
5242880 bytes (5.2 MB) copied, 0.0218812 s, 240 MB/s

$ ls -lrth *
2:
total 0

1:
total 5.0M
-rw-r--r-- 1 andre wheel 5.0M Sep 13 17:32 somefile

$ ln 1/somefile 2/somefile-hard-link
$ ls -lrth *
1:
total 5.0M
-rw-r--r-- 2 andre wheel 5.0M Sep 13 17:32 somefile

2:
total 5.0M
-rw-r--r-- 2 andre wheel 5.0M Sep 13 17:32 somefile-hard-link

$ du -ksh *
5.0M    1
0       2

$ rm 1/somefile

$ ls -lrth *
2:
total 5.0M
-rw-r--r-- 1 andre wheel 5.0M Sep 13 17:32 somefile-hard-link

1:
total 0

$ du -ksh *
0       1
5.0M    2

Nice, hm?