Tag Archives: Ubuntu

Debian/Ubuntu’s apt behind a proxy

To allow the Advanced Packaging Tool, or just APT for friends to do its job when the box is behind a proxy, we can use one of the following options.

From the command line (this will only work for the session we are working on):

export http_proxy=http://username:password@server:port

Or if the proxy does not require a username:

export http_proxy=http://server:port

Another option is to add the following line into the file /etc/apt/apt.conf (note the semicolon at the end):

Acquire::http::Proxy "http://username:password@server:port";

Install VMWare ESXi using a USB flash drive

Today, I decided to try the VMWare ESXi, the free bare metal virtualization product of VMWare, on an old Pentium 4 3.2GHz PC (with 2.5GB of RAM), and run on top of it, some Ubuntu servers.

I was not able to use the latest version (4.x) of the ESXi as it only works on 64-bit boxes. Instead, the version 3.5 does work on 32-bit processors as the one I’m using.

As I didn’t want to burn a CD with the installer, I chose to use an USB stick to make the installation. So, the first thing to do was converting the ISO installer into a USB, using this software. I had a little problem, that I solved in some minutes with the help of Google.

After that, the installation ran without problems (there is a nice ESXi installation guide here) and the server was up and running some minutes later.

Then, I just unplugged the monitor, keyboard and mouse from that PC, as they are not gonna be needed anymore. I installed the VMWare vSphere Client on my main machine to manage the server.

So far, I have installed two Ubuntu Linux servers and they are running with not bad performance, at least, enough for testing and development.

Resolving troubleshooting with Munin

This are some problems that you may encounter after installing Munin:

Apache modules are not tracking, so they are not showing statistics, you may want to check Munin logs (specifically /var/log/munin/munin-node.log) to see what is going on.

If you got something like Can’t locate object method “new” via package “LWP::UserAgent”, you need to install the package libwww-perl which contains the LWP::UserAgent required. Thanks to Crowdway.

If you already have installed the libwww-perl package, but Munin is still not showing data, you may need to enable and configure the status module on Apache. Make sure you allow localhost (and the name of the server as well) to access the location server-status on apache2.conf or status.conf. Also, this plugins need the ExtendedStatus flag to be On.

You should have something like:

<IfModule mod_status.c>
#
# Allow server status reports generated by mod_status,
# with the URL of http://servername/server-status
# Uncomment and change the ".example.com" to allow
# access from other hosts.
#
ExtendedStatus On
<Location /server-status>
    SetHandler server-status
    Order deny,allow
    Deny from all
    Allow from localhost ip6-localhost
    Allow from vps02.graphium.net
    #Allow from .example.com
</Location>
<IfModule>

Sometimes you can get permission errors on your logs, so the best way to get rid of them is to ensure that all involved files in Munin process are own by munin user and group. We can run as root:

 $ chown -R munin.munin /var/lib/munin /var/log/munin /var/www/munin

There are some plugins that require a parameter to work. For example, those that refer to networking (if_, if_err_, ip_) needs the network interface we want to track. In my case (VPS), this is venet0, but on a usual box it can be eth0.

We can list the available interfaces by running the command:

$ ifconfig

Then, to correctly enable this modules, we need to append the name of the interface:

$ ln -s /usr/share/munin/plugins/if_ /etc/munin/plugins/if_venet0

A convenient way to see the result of each module, we can run them independently:

$ munin-run apache_processes
busy80.value 7
idle80.value 1
$ munin-run if_venet0
down.value 7721322
up.value 37550800

By this command, we can ensure that the plugin is working fine and getting results.

Install Munin on Ubuntu Server

Munin is a small tool for monitoring resources on servers. I think it is very useful, specially on small VPS, that needs to save resources. Reports are written as HTML files, so we will need a Web Server like Apache to see this reports.

First, we install it and add some extra plugins:

$ sudo apt-get install munin munin-plugins-extra

Now, we can make some changes to the default configuration, located at /etc/munin/munin.conf. For example, we can change any of the paths where Munin works:

dbdir /var/lib/munin
htmldir /var/www/munin
logdir /var/log/munin
rundir /var/run/munin

Specially, the htmldir path, where all the reports are written to see through Apache or the one you are using. Remember to move the directory /var/www/munin to where you wanted if you change that configuration line. We can protect this directory with an htaccess file to only give access to some users.

We can configure email notifications if a change occur (like from a OK situation to a WARNING). To do this, we just need to uncomment or add the following line:

contact.someuser.command mail -s "Munin notification" your@email.com

By default, Munin will monitor localhost, but we can add other boxes (clients), these machines will only need to install munin-node package.

Then, we can enable some plugins (more plugins can be found here and here). To do this, we need to create a symbolic link per each plugin we want to activate. I’m going to enable apache and mysql modules, but you are free to enable the modules you need:

$ cd /etc/munin/plugins
$ sudo ln -s /usr/share/munin/plugins/apache_* .
$ sudo ln -s /usr/share/munin/plugins/mysql_* .

Each time a module is enable or disable, we need to restart the service, so we can do the following:

$ sudo /etc/init.d/munin-node restart

Also, it is recommended to reassign all files on the htmldir to munin user and group by doing:

$ sudo chown munin.munin -R /var/www/munin

And then, to avoid waiting 5 minutes until munin cron runs again, we force it by:

$ sudo /usr/bin/munin-cron --force-root

If we are not completely satisfied with the default template, we can modify it, they are HTML files (with some minor special template tags). Anyone with some knowledge of HTML and CSS can do that. We can even download other already created templates (I have found some errors on that template’s JavaScript, I hope I’ll get some time to post the modified template, in the meanwhile, if anyone need it, please drop me a line to send you the files).

Finally, as this post is not as complete as I would like, I leave some links that may help:

Cambiar la contraseña de un usuario en MySQL

Hay varios métodos para cambiar la contraseña de un usuario en MySQL, pero este es el que me parece más seguro ya que no deja rastro de la contraseña antigua ni nueva en el historial de comandos (por lo menos en bash).

Primero, nos logueamos al shell de MySQL con el usuario principal:

$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 111
Server version: 5.0.75-0ubuntu10 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Escogemos la base de datos mysql:

use mysql;

Cambiamos los registros de la tabla user que almacenan la contraseña del usuario que queramos:

update user set password=PASSWORD("nuevacontraseña") where user='usuario';

Si quisieramos dejar al usuario con la contraseña en blanco, hacemos lo siguiente:

update user set password=NULL where user='usuario';

Limpiamos y volvemos a cargar los privelegios:

flush privileges;

Y salimos:

mysql> quit

Desinstalar kernels antiguos en Ubuntu

Tras cada actualización del kernel de Linux, los anteriores quedan como recuerdo en el disco duro. El inconveniente principal de esto es que cada vez que arranques tu máquina, el menú del Grub (o Lilo quizá, aunque si usas Ubuntu, es poco probable que lo tengas) será cada vez más largo y con opciones (kernels antiguos) que muy probablemente no vuelvas a utilizar.

La solución a esto es desinstalar cada cierto tiempo los kernels obsoletos. En Ubuntu, podemos hacerlo de la siguiente manera:

Ver primero que versión del kernel estamos usando con el comando:

uname -r

Esto arrojará algo como:

2.6.28-13-generic

Ver que otras versiones tienen instaladas (a la izquierda de cada linea, hay una letra, todas las que tengan la letra i serán las que están en el sistema):

sudo aptitude search linux-image-2

Luego, desde consola ejecutamos el comando:

sudo apt-get remove --purge 2.6.28-11-*

Teniendo en cuenta que 2.6.28-11 es la versión que queremos quitar (OJO, deben reemplazar este valor por la versión que quieran quitar, que no sea la versión actual y preferiblemente dejen las dos últimas versiones por si la más nueva tiene algún problema).

El resultado de este comando será algo similar a esto (seguramente con variaciones dependiendo que tengan instalado):

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Couldn't find package 2.6.28-11
yorch@blackbird:~$ sudo apt-get remove --purge 2.6.28-11-*
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting linux-image-2.6.28-11-generic for regex '2.6.28-11-*'
Note, selecting linux-headers-lbm-2.6.28-11-server for regex '2.6.28-11-*'
Note, selecting linux-image-2.6.28-11-server for regex '2.6.28-11-*'
Note, selecting linux-headers-2.6.28-11-generic for regex '2.6.28-11-*'
Note, selecting linux-headers-2.6.28-11-server for regex '2.6.28-11-*'
Note, selecting linux-headers-2.6.28-11 for regex '2.6.28-11-*'
Note, selecting linux-backports-modules-2.6.28-11-server for regex '2.6.28-11-*'
Note, selecting linux-backports-modules-2.6.28-11-generic for regex '2.6.28-11-*'
Note, selecting linux-restricted-modules-2.6.28-11-server for regex '2.6.28-11-*'
Note, selecting linux-restricted-modules-2.6.28-11-generic for regex '2.6.28-11-*'
Note, selecting linux-headers-lbm-2.6.28-11-generic for regex '2.6.28-11-*'
Note, selecting linux-image-2.6.28-11-virtual for regex '2.6.28-11-*'
The following packages will be REMOVED:
  linux-headers-2.6.28-11* linux-headers-2.6.28-11-generic* linux-image-2.6.28-11-generic*
  linux-restricted-modules-2.6.28-11-generic*
0 upgraded, 0 newly installed, 4 to remove and 0 not upgraded.
After this operation, 190MB disk space will be freed.
Do you want to continue [Y/n]? y
(Reading database ... 369744 files and directories currently installed.)
Removing linux-headers-2.6.28-11-generic ...
Removing linux-headers-2.6.28-11 ...
Removing linux-restricted-modules-2.6.28-11-generic ...
update-initramfs: Generating /boot/initrd.img-2.6.28-11-generic
Purging configuration files for linux-restricted-modules-2.6.28-11-generic ...
Removing linux-image-2.6.28-11-generic ...
Examining /etc/kernel/prerm.d.
run-parts: executing /etc/kernel/prerm.d/dkms
Uninstalling: vboxnetflt 2.1.4 (2.6.28-11-generic) (x86_64)

-------- Uninstall Beginning --------
Module:  vboxnetflt
Version: 2.1.4
Kernel:  2.6.28-11-generic (x86_64)
-------------------------------------

Status: Before uninstall, this module version was ACTIVE on this kernel.

vboxnetflt.ko:
 - Uninstallation
   - Deleting from: /lib/modules/2.6.28-11-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
depmod....

DKMS: uninstall Completed.
Uninstalling: vboxdrv 2.1.4 (2.6.28-11-generic) (x86_64)

-------- Uninstall Beginning --------
Module:  vboxdrv
Version: 2.1.4
Kernel:  2.6.28-11-generic (x86_64)
-------------------------------------

Status: Before uninstall, this module version was ACTIVE on this kernel.

vboxdrv.ko:
 - Uninstallation
   - Deleting from: /lib/modules/2.6.28-11-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
depmod....

DKMS: uninstall Completed.
Uninstalling: virtualbox-ose-guest 2.1.4 (2.6.28-11-generic) (x86_64)

-------- Uninstall Beginning --------
Module:  virtualbox-ose-guest
Version: 2.1.4
Kernel:  2.6.28-11-generic (x86_64)
-------------------------------------

Status: Before uninstall, this module version was ACTIVE on this kernel.

vboxadd.ko:
 - Uninstallation
   - Deleting from: /lib/modules/2.6.28-11-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.

vboxvfs.ko:
 - Uninstallation
   - Deleting from: /lib/modules/2.6.28-11-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.
depmod....

DKMS: uninstall Completed.
run-parts: executing /etc/kernel/prerm.d/last-good-boot
Running postrm hook script /sbin/update-grub.
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... found: /boot/grub/default
Testing for an existing GRUB menu.lst file ... found: /boot/grub/menu.lst
Searching for splash image ... none found, skipping ...
Found kernel: /boot/vmlinuz-2.6.28-13-generic
Found kernel: /boot/memtest86+.bin
Replacing config file /var/run/grub/menu.lst with new version
Updating /boot/grub/menu.lst ... done

Purging configuration files for linux-image-2.6.28-11-generic ...
Running postrm hook script /sbin/update-grub.
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... found: /boot/grub/default
Testing for an existing GRUB menu.lst file ... found: /boot/grub/menu.lst
Searching for splash image ... none found, skipping ...
Found kernel: /boot/vmlinuz-2.6.28-13-generic
Found kernel: /boot/memtest86+.bin
Updating /boot/grub/menu.lst ... done

dpkg - warning: while removing linux-image-2.6.28-11-generic, directory `/lib/modules/2.6.28-11-generic' not empty so not removed.

Luego pueden repetir el proceso para el resto de versiones que deseen.

Cloud Computing en el mundo del Web Hosting

Encontré este artículo sobre el Cluod Computing, específicamente en el mercado del web hosting y como está revolucionando una industria que no ha sufrido de cambios importantes en los últimos años (nada más allá del incremento de espacio, procesamiento y ancho de banda). Vale la pena leerlo.

Además, ya existen plataformas open-source como esta y esta, que permiten convertir la infraestructura actual en una verdadera Cloud Computing.

Por último, también queria comentar sobre el nuevo servicio (lanzado recién esta semana) que ofrece Mosso (del gigante Rackspace) en lo que es servidores on demand, Cloud Servers, un concepto similar al Amazon EC2 (Elastic Compute Cloud), pero con la ventaja de poder contratar instancias (servidores) más pequeños (desde 256MB de RAM).

Permite trabajar con varias distribuciones de Linux (incluida Ubuntu :D) y a diferencia del servicio de Amazon, existe persistencia en la data (si apagamos una instancia de EC2, toda la informacion del servidor se pierde). Lo he estado probando algunos días y va muy bien (instale el Tomcat y el PostgreSQL), aunque aún hay cosas que mejorar, como permitir que los backups que se hacen de los servidores, sigan existiendo a pesar de eliminar el servidor (para evitar que sigan cobrando por el, y que podamos levantarlo en otro momento cuando lo necesitemos).

Voy a seguir probandolo algunos días más, y si todo va bien, le doy de baja al VPS que tengo con eApps (que lo uso básicamente para mis repositorios de Subversion) y me quedo con Cloud Servers.

Usar una IP estática en Ubuntu Intrepid

Luego de repetidos intentos de colocarle una IP estática a mi máquina utilizando el NetworkManager que viene por defecto, ésta es reseteada y establecida por DHCP en cada reinicio (no quería meterle mano directamente al archivo /etc/network/interfaces). Según lo que encontré, esto es un bug del dichoso programa. Algunos sugiren desinstarlo, pero yo no buscaba una solución tan drástica. Afortunamente encontré un workaround. Aún no reinicio mi computadora para ver si realmente funciona, pero todo indica que sí.

Otra opción sería instalar Wicd, una alternativa al NetworkManager.

Caracteres ASCII en Ubuntu

Mientras escribía el post anterior, me ví en la necesidad de utilizar un caracter ASCII que no se encontraba en mi teclado, hablo de ~, que en Linux representa el directorio home del usuario actual. En Windows, podría haber utilizado el Alt + 164 para colocarlo, pero esto no funciona en Ubuntu (ni en otras distrbuciones de Linux).

Luego de buscar algunos minutos en Google, no encontre nada que me permita usar Alt + código para agregar caracteres especiales. Lo interesante que encontré fue que al presionar AltGr + 4, obtengo dicho caracter. Si utilizo AltGr con el resto de teclas del teclado, se consiguen muchos otros caracteres que nos pueden resultar útiles.

Convertir una clave PuTTY en una OpenSSH

Si sabes que es PuTTY y lo utilizas con alguna regularidad, es probable que en algún momento necesites convertir una de sus claves privadas al formato OpenSSH para utilizarla en linux. ¿A que me refiero? a hacer algo como:

ssh usuario@servidor

desde una consola de linux y entrar directamente al servidor, sin tener que estar recordando ni escribiendo la contraseña cada vez.

Vamos a necesitar la herramienta puttygen (que se encuentra dentro del paquete putty-tools) para hacer la conversión. Desde Ubuntu (o desde cualquier otra distribución basada en Debian), basta con:

sudo apt-get install putty-tools

Una vez que tenemos instalado dicha herramienta, creamos el directorio .ssh (donde guardaremos nuestra clave) en nuestro home, en caso no esté creado:

mkdir ~/.ssh

Luego, le cambiamos los permisos para que solo sea accesible por nuestro usuario:

chmod 700 ~/.ssh

Después, procedemos a realizar la conversión (puedes ver todas las opciones del comando puttygen aquí):

puttygen nombre-de-nuestra-clave-de-putty.ppk -O private-openssh -o ~/.ssh/id_rsa

Si nuestra clave de PuTTY tiene un passphrase, nos lo va a pedir.

Luego, nos aseguramos que los permisos de la clave recién creada sean los correctos:

chmod 600 ~/.ssh/id_rsa

Finalmente, solo bastará con colocar el passphrase una vez durante toda nuestra sesión y podremos conectarnos a los equipos que queramos sin necesidad de la contraseña.

PD, encontré que el procedimiento contrario (de una clave OpenSSH a una de PuTTY) está explicado acá.