En este tutorial vamos a ver cómo realizar sincronización de ficheros entre dos servidores Ubuntu usando una herramienta de nombre Unison. Unison es una herramienta de sincronización similar a rsync (tengo algún articulo sobre rsync en el site), la gran diferencia respecto a ella es que Unison traza/sincroniza cambios bidireccionalmente, ficheros modificados en el servidor 1 serán replicados en el servidor 2 y vice versa.

Notas preliminares

foto de Eloy Mier Pérez
En este tutorial voy a hacer uso de los siguientes dos servidores Ubuntu 11.10:

  • server1.example.com con dirección IP 192.168.0.100
  • server2.example.com con dirección IP 192.168.0.101
La idea del ejemplo es la sincronización del directorio /var/www entre ambos servidores. Unison lo voy a ejecutar como usuario root de forma que la herramienta tenga los privilegios suficientes para sincronizar los permisos de grupo y de usuario.
Los pasos a dar en el tutorial los vamos a realizar como root, asi que aseguremonos de ser root:
sudo su

Instalando Unison

Unison debe ser instalado tanto en el servidor1 como en el servidor2; además como vamos a conectar desde el servidor1 al servidor2 usando ssh, vamos a necesitar tambien los paquetes relativos a SSH. Para lograrlo debemos ejecutar:

apt-get install unison openssh-server ssh

Creación de claves privada/publica en el servidor 1

Ahora vamos a crear el par de claves privada/publica en el servidor server1.example.com:

ssh-keygen -t dsa
root@server1:~# ssh-keygen -t dsa Generating public/private dsa key pair. Enter file in which to save the key (/root/.ssh/id_dsa): <-- ENTER Created directory '/root/.ssh'. Enter passphrase (empty for no passphrase): <-- ENTER Enter same passphrase again: <-- ENTER Your identification has been saved in /root/.ssh/id_dsa. Your public key has been saved in /root/.ssh/id_dsa.pub. The key fingerprint is: 32:0f:f5:49:f0:32:f8:d0:63:8d:44:88:a5:12:f9:73 root@server1.example.com The key's randomart image is: +--[ DSA 1024]----+ |  .. o.o+        | |  .....+ =       | |  ... o O +      | |   .o E= * .     | |     o+ S o      | |       =         | |        .        | |                 | |                 | +-----------------+ root@server1:~#

Es importante no introducir una clave de paso pues si la indicamos la sincronización no va a funcionar sin la intervención del usuario, por lo tanto cuando nos la pida, simplemente pulsad ENTER!.

El siguiente paso será copiar la clave pública al servidor server2.example.com (en este servidor debe estar habilitada la cuenta de root y activado el loggin remoto). Para habilitar el loggin de root en un sistema Ubuntu simplemente le asignamos una contraseña a la cuenta de root:

sudo passwd root

Para verificar que la cuenta de root puede conectar mediante ssh debemos echar un vistazo a la directiva PermitRootLogin en el fichero /etc/ssh/sshd_config. Después de cualquier cambio en este fichero, deberemos re arrancar el servicio ssh.

Retomando el asunto de la clave, vamos a proceder a la copia de la misma:

ssh-copy-id -i $HOME/.ssh/id_dsa.pub root@192.168.0.101

root@server1:~# ssh-copy-id -i $HOME/.ssh/id_dsa.pub root@192.168.0.101
The authenticity of host '192.168.0.101 (192.168.0.101)' can't be established.
ECDSA key fingerprint is a2:38:f3:df:7a:6c:b6:3c:d6:c3:9c:88:93:e2:f0:63.
Are you sure you want to continue connecting (yes/no)? <-- yes (you will see this only if this is the first time you connect to server2)
Warning: Permanently added '192.168.0.101' (ECDSA) to the list of known hosts.
root@192.168.0.101's password: <-- server2 root password
Now try logging into the machine, with "ssh 'root@192.168.0.101'", and check in:

~/.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

root@server1:~#

Ahora debemos verificar en server2.example.com que la clave publica de server1 ha sido correctamente transferida:

cat $HOME/.ssh/authorized_keys <pre>ssh-dss AAA....+UjQ== root@server1.example.com</pre> 

Ejecutando Unison

Ahora vamos a ejecutar Unison por primera vez para sincronizar el directorio /var/www en ambos servidores. En server1.example.com ejecutamos:

unison /var/www ssh://192.168.0.101//var/www

La salida será similar a esta – Es posible que tengas que responder algunas preguntas al ser esta la primera ejecucion:

root@server1:~# unison /var/www ssh://192.168.0.101//var/www
Contacting server...
Connected [//server1.example.com//var/www -&gt; //server2.example.com//var/www]
Looking for changes
Warning: No archive files were found for these roots, whose canonical names are:
/var/www
//server2.example.com//var/www
This can happen either because this is the first time you have synchronized these roots,
or because you have upgraded Unison to a new version with a different archive format.

Update detection may take a while on this run if the replicas are large.

Unison will assume that the 'last synchronized state' of both replicas
was completely empty.  This means that any files that are different
will be reported as conflicts, and any files that exist only on one
replica will be judged as new and propagated to the other replica.
If the two replicas are identical, then no changes will be reported.

If you see this message repeatedly, it may be because one of your machines
is getting its address from DHCP, which is causing its host name to change
between synchronizations.  See the documentation for the UNISONLOCALHOSTNAME
environment variable for advice on how to correct this.

Donations to the Unison project are gratefully accepted:
http://www.cis.upenn.edu/~bcpierce/unison

Waiting for changes from server| webalizer
Reconciling changes

local          server2.e...
dir      ----&gt;            apps  [f] &lt;-- ENTER
file     ----&gt;            index.html  [f] &lt;-- ENTER
link     ----&gt;            ispconfig  [f] &lt;-- ENTER
dir      ----&gt;            php-fcgi-scripts/apps  [f] &lt;-- ENTER
dir      ----&gt;            webalizer  [f] &lt;-- ENTER
link     ----&gt;            webmail  [f] &lt;-- ENTER

Proceed with propagating updates? [] &lt;-- y
Propagating updates

UNISON 2.32.52 started propagating changes at 14:25:02 on 09 Dec 2011
[BGN] Copying apps from /var/www to //server2.example.com//var/www
[BGN] Copying index.html from /var/www to //server2.example.com//var/www
[BGN] Copying ispconfig from /var/www to //server2.example.com//var/www
[BGN] Copying php-fcgi-scripts/apps from /var/www to //server2.example.com//var/www
[BGN] Copying webalizer from /var/www to //server2.example.com//var/www
[BGN] Copying webmail from /var/www to //server2.example.com//var/www
[END] Copying ispconfig
[END] Copying webmail
[END] Copying apps
[END] Copying webalizer
[END] Copying index.html
[END] Copying php-fcgi-scripts/apps
UNISON 2.32.52 finished propagating changes at 14:25:03 on 09 Dec 2011

Saving synchronizer state
Synchronization complete at 14:25:03  (6 items transferred, 0 skipped, 0 failed)
root@server1:~#

Ahora procedamos a verificar el directorio /var/www tanto en server1 como en server2, y debiéramos ver que se encuentran a nivel.

Por supuesto, que si no queremos ejecutar Unison de forma interactiva, podremos crear un fichero de preferencias (/root/.unison/default.prf) que contendrá la configuración que de otra forma debemos proporcionar a través de la línea de comandos:

vi /root/.unison/default.prf
# Unison preferences file
# Roots of the synchronization
root = /var/www
root = ssh://192.168.0.101//var/www

# Paths to synchronize
#path = current
#path = common
#path = .netscape/bookmarks.html

# Some regexps specifying names and paths to ignore
#ignore = Path stats    ## ignores /var/www/stats
#ignore = Path stats/*  ## ignores /var/www/stats/*
#ignore = Path */stats  ## ignores /var/www/somedir/stats, but not /var/www/a/b/c/stats
#ignore = Name *stats   ## ignores all files/directories that end with "stats"
#ignore = Name stats*   ## ignores all files/directories that begin with "stats"
#ignore = Name *.tmp    ## ignores all files with the extension .tmp

#When set to true, this flag causes the user interface to skip
#asking for confirmations on non-conflicting changes. (More
#precisely, when the user interface is done setting the
#propagation direction for one entry and is about to move to the
#next, it will skip over all non-conflicting entries and go
#directly to the next conflict.)
auto=true

# When this is set to true, the user interface will ask no
# questions at all. Non-conflicting changes will be propagated;
# conflicts will be skipped.
batch=true

# !When this is set to true, Unison will request an extra
# confirmation if it appears that the entire replica has been
# deleted, before propagating the change. If the batch flag is
# also set, synchronization will be aborted. When the path
# preference is used, the same confirmation will be requested for
# top-level paths. (At the moment, this flag only affects the
# text user interface.) See also the mountpoint preference.
confirmbigdel=true

# When this preference is set to true, Unison will use the
# modification time and length of a file as a `pseudo inode
# number' when scanning replicas for updates, instead of reading
# the full contents of every file. Under Windows, this may cause
# Unison to miss propagating an update if the modification time
# and length of the file are both unchanged by the update.
# However, Unison will never overwrite such an update with a
# change from the other replica, since it always does a safe
# check for updates just before propagating a change. Thus, it is
# reasonable to use this switch under Windows most of the time
# and occasionally run Unison once with fastcheck set to false,
# if you are worried that Unison may have overlooked an update.
# The default value of the preference is auto, which causes
# Unison to use fast checking on Unix replicas (where it is safe)
# and slow checking on Windows replicas. For backward
# compatibility, yes, no, and default can be used in place of
# true, false, and auto. See the section "Fast Checking" for more
# information.
fastcheck=true

# When this flag is set to true, the group attributes of the
# files are synchronized. Whether the group names or the group
# identifiers are synchronizeddepends on the preference numerids.
group=true

# When this flag is set to true, the owner attributes of the
# files are synchronized. Whether the owner names or the owner
# identifiers are synchronizeddepends on the preference
# extttnumerids.
owner=true

# Including the preference -prefer root causes Unison always to
# resolve conflicts in favor of root, rather than asking for
# guidance from the user. (The syntax of root is the same as for
# the root preference, plus the special values newer and older.)
# This preference is overridden by the preferpartial preference.
# This preference should be used only if you are sure you know
# what you are doing!
prefer=newer

# When this preference is set to true, the textual user interface
# will print nothing at all, except in the case of errors.
# Setting silent to true automatically sets the batch preference
# to true.
silent=true

# When this flag is set to true, file modification times (but not
# directory modtimes) are propagated.
times=true</pre>

Los comentarios en el fichero son auto explicativos a excepción de las directivas path. Si no se especifican directivas path, se sincronizarán los directorios especificados en las directivas root. Si se especifican directivas path, entonces las rutas pasan a ser relativas a los directorios especificados por la directiva root (ej. root=/var/www y path=current se traduce en /var/www/current) y solo esos subdirectorios son sincronizados, y no lo es la ruta completa especificada por la directiva root.

Para obtener más información sobre las opciones disponibles para Unison puedes consultar su página de man:

man unison

Ahora que ya hemos escrito todas las preferencias en el fichero correspondiente de Unison, ahora podemos usar Unison sin argumentos:

unison

Programando Unison mediante cron

Si queremos automatizar la sincronización, podemos hacerlo usando cron del sistema definiendo para ello una tarea. Recuerdo a los lectores el artículo hace no mucho tiempo escribí en parte sobre el asunto de cron y que podéis encontrar [intlink id=»2382″ type=»post»]aquí[/intlink].

Para la edición del fichero de tareas de cron se emplea el siguiente comando:

crontab -e

Agregamos la ejecución de nuestro comando (revisad el artículo indicado anteriormente para mas detalle del mismo):

<pre>*/5 * * * * /usr/bin/unison & > /dev/null</pre>

El comando anterior ejecutará Unison cada 5 minutos; ajustalo a tus necesidades. En el comando se puede apreciar el uso de la ruta completa al comando Unison, simplemente para asegurar que cron sabe donde localizar dicho comando. La ubicación de Unison podría variar de un sistema a otro. Para saber donde tienes ubicado el comando:

which unison

Enlaces

You must be logged in to post a comment.