GNU/Linux >> Tutoriels Linux >  >> Debian

Configuration de la synchronisation de fichiers Unison entre deux serveurs sur Debian 8 (Jessie)

Ce tutoriel montre comment configurer la synchronisation de fichiers entre deux serveurs Debian 8 avec Unison. Unison est un outil de synchronisation de fichiers similaire à rsync, la grande différence est qu'il suit/synchronise les changements dans les deux sens, c'est-à-dire que les fichiers modifiés sur le serveur1 seront répliqués sur le serveur2 et vice versa.

1 Remarque préliminaire

Dans ce tutoriel, j'utiliserai les deux serveurs Debian suivants :

  • server1.example.com avec l'adresse IP 192.168.1.101
  • server2.example.com avec l'adresse IP 192.168.1.102

Je souhaite synchroniser le répertoire /var/www entre les deux serveurs. Je vais exécuter Unison en tant qu'utilisateur root dans ce didacticiel afin qu'Unison dispose des autorisations suffisantes pour synchroniser les autorisations des utilisateurs et des groupes.

Toutes les commandes de ce didacticiel sont exécutées en tant qu'utilisateur root. Connectez-vous aux deux serveurs sur le shell en tant que root et commencez par l'étape 2 "Installation d'Unison ".

2 Installer Unison

serveur1/serveur2 :

Unison doit être installé sur le serveur1 et le serveur2 ; puisque nous nous connectons de server1 à server2 en utilisant SSH, nous avons également besoin des packages SSH et j'installerai l'éditeur nano pour l'édition de fichiers sur le shell. Ceci peut être réalisé comme suit :

apt-get -y install unison openssh-server ssh nano

3 Création d'une paire de clés privée/publique sur le serveur1

serveur1 :

Nous créons maintenant une paire de clés privée/publique sur server1.example.com :

ssh-keygen -t dsa

[email protected] :~# ssh-keygen -t dsa
Génération d'une paire de clés dsa publique/privée.
Entrez le fichier dans lequel enregistrer la clé (/root/.ssh/id_dsa) : <-- ENTER
Répertoire créé '/root/.ssh'.
Saisissez la phrase de passe (vide pour aucune phrase de passe) : <-- ENTER
Saisissez à nouveau la même phrase de passe  : <-- ENTER
Votre l'identification a été enregistrée dans /root/.ssh/id_dsa.
Votre clé publique a été enregistrée dans /root/.ssh/id_dsa.pub.
L'empreinte de la clé est :
ba :82 :e1:a1:42:9b:d4:c8:99:c8:bd:8b:7d:4d:d4:66 [email protected]
L'image aléatoire de la clé est :
+--- [DSA 1024]----+
| |
| |
| . |
| . E |
|+ * . S |
|.Ooo o |
|ooo+. + |
|oo=... o |
|.. oo.. |
+-----------------+
[e-mail protégé] :~#

Il est important que vous ne saisissiez pas de phrase de passe, sinon la mise en miroir ne fonctionnera pas sans interaction humaine, alors appuyez simplement sur ENTRÉE !

Ensuite, nous copions notre clé publique sur server2.example.com :

ssh-copy-id -i $HOME/.ssh/id_dsa.pub [email protected]
# ssh-copy-id -i $HOME/.ssh/id_dsa.pub [email protected]
The authenticity of host '192.168.1.102 (192.168.1.102)' can't be established.
ECDSA key fingerprint is 51:7f:b4:ed:bd:e3:fc:16:2f:55:5c:e1:2c:d7:3d:a9.
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)
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password: <-- server2 root password
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.

Vérifiez maintenant sur le serveur2 si la clé publique du serveur1 a bien été transférée :

serveur2 :

cat $HOME/.ssh/authorized_keys
[email protected]:/home/administrator# cat $HOME/.ssh/authorized_keys
ssh-dss AAAAB3NzaC1kc3MAAACBAKHLdAztIr8muZIlQYuE/4f75kmgTwWqJRZJ1dTqHDnHWsy48emDU8v85hxAPg43k9aF7/zAwpA0MNNNk5T9Tx/DyUkK/KcyVP2f4p8tvovrkUvoxsZACkTUmFqKdq2x6/AGfjsCRmkpLhZuad7r5rKEXHRh8KYGHqD1Id8wcpy5AAAAFQCww3OekKcKMshMAwBK3XQmmYEGUwAAAIEAgjztlwh8OFYxwQve/RrhI2sceCXwS/yjQyH7q0zdWB9Fr4s/16T2PLBT+7M3vb+JlPDO3JRqgaYbel1kS2F2iKrY0EX0FI3/9fVDfWoz3mhCscPLriqy5AcsHitxQNfiZgA5wDiSjWpk1v+FbIC+VuqbKdQuE4MBKj19N9YALIUAAACABQ4NDsa2UBc8jsxvghjoLhUWF7HChaCksXQcL6i98VNRcemtPC6wpIri75iR4Uhv1666bDOBAdmIBX9Qf7A/+czPKPaj4CGI1hVy1pgYMa3btnEvoSnH/ONtjpOz9q+3up1OOOn+5fud7xjJn+Fq8WoGROgarBpCbQU3w2GUUnM= [email protected]

4 Courir à l'unisson

serveur1 :

Nous pouvons maintenant exécuter Unison pour la première fois pour synchroniser le répertoire /var/www sur les deux serveurs. Sur le serveur1, exécutez :

unison /var/www ssh://192.168.1.102//var/www

La sortie sera similaire à celle-ci - vous devrez peut-être répondre à quelques questions car c'est la première fois qu'Unison est exécuté :

[email protected]:/var/www# unison /var/www ssh://192.168.1.102//var/www
Contacting server...
Connected [//server1//var/www -> //server2//var/www]
Looking for changes
Warning: No archive files were found for these roots, whose canonical names are:
/var/www
//server2//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
Press return to continue.[<spc>] <-- Press Enter
Waiting for changes from server
Reconciling changes
local server2
dir ----> example.com [f] <-- Press Enter
dir ----> example.de [f] <-- Press Enter
Proceed with propagating updates? [] <-- Enter "y"
Propagating updates

UNISON 2.40.102 started propagating changes at 10:17:17.94 on 25 Sep 2015
[BGN] Copying example.com from /var/www to //server2//var/www
[BGN] Copying example.de from /var/www to //server2//var/www
Shortcut: copied /var/www/example.de/web/index.html from local file /var/www/.unison.example.com.d3783bddaaf59b9ba4d2ed0433f9db63.unison.tmp/web/index.html
[END] Copying example.de
[END] Copying example.com
UNISON 2.40.102 finished propagating changes at 10:17:17.94 on 25 Sep 2015

Saving synchronizer state
Synchronization complete at 10:17:17 (2 items transferred, 0 skipped, 0 failed)

Vérifiez le répertoire /var/www sur le serveur1 et le serveur2 maintenant, et vous devriez constater qu'ils sont maintenant synchronisés.

Bien sûr, nous ne voulons pas exécuter Unison de manière interactive, nous pouvons donc créer un fichier de préférences (/root/.unison/default.prf) qui contient tous les paramètres que nous devrions autrement spécifier sur la ligne de commande :

nano /root/.unison/default.prf
# Roots of the synchronization
root = /var/www
root = ssh://192.168.1.102//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

Les commentaires doivent rendre le fichier explicite, à l'exception des directives de chemin. Si vous ne spécifiez aucune directive de chemin, les répertoires des directives racine seront synchronisés. Si vous spécifiez des directives de chemin, les chemins sont relatifs au chemin racine (par exemple, racine =/var/www et chemin =courant se traduit par /var/www/courant), et seuls ces sous-répertoires seront synchronisés, et non l'ensemble du répertoire spécifié dans la directive racine.

Vous pouvez en savoir plus sur les options disponibles en consultant la page de manuel d'Unison :

man unison

Maintenant que nous avons mis tous les paramètres dans un fichier de préférences (en particulier les directives root (et éventuellement le chemin)), nous pouvons exécuter Unison sans aucun argument :

unison

5 Créer une tâche Cron pour Unison

serveur1 :

Nous voulons automatiser la synchronisation, c'est pourquoi nous créons une tâche cron pour celle-ci sur server1.example.com :

crontab -e
*/5 * * * * /usr/bin/unison &> /dev/null

Cela exécuterait Unison toutes les 5 minutes; adaptez-le à vos besoins (voir

man 5 crontab

). J'utilise le chemin complet vers l'unisson ici (/usr/bin/unison) juste pour m'assurer que cron sait où trouver l'unisson. Votre emplacement d'unisson peut différer. Exécuter

which unison

pour savoir où se trouve le vôtre.

6 Tester l'unisson

Je vais maintenant tester la synchronisation bidirectionnelle d'Unison pour voir si la configuration fonctionne parfaitement.

Exécutez la commande suivante sur le serveur1 pour créer un fichier de test avec le contenu "Test 1":

Serveur1

echo "Test 1" > /var/www/test.txt

Attendez maintenant au moins 5 minutes (car nous avons créé un cronjob qui s'exécute une fois toutes les 5 minutes). Exécutez ensuite sur le serveur2 :

cat /var/www/test.txt

pour afficher le contenu du fichier test.txt à l'écran. La sortie devrait ressembler à cette capture d'écran.

Exécutez maintenant cette commande sur le serveur2 qui met à jour le contenu de notre fichier de test en "Test 2":

Serveur2

echo "Test 2" > /var/www/test.txt

Et attendez au moins 5 minutes. Exécutez ensuite la commande cat sur le serveur1 :

Serveur1

cat /var/www/test.txt

Le résultat devrait être comme indiqué sur la capture d'écran.

  • Unison :http://www.cis.upenn.edu/~bcpierce/unison/
  • Debian :http://www.debian.org/

Debian
  1. Comment mettre à niveau Debian 8 Jessie vers Debian 9 Stretch

  2. Stockage haute disponibilité avec GlusterFS sur Debian Lenny - Réplication automatique de fichiers sur deux serveurs de stockage

  3. Stockage haute disponibilité avec GlusterFS 3.0.x sur Debian Squeeze - Réplication automatique des fichiers sur deux serveurs de stockage

  4. Debian – Utiliser deux écrans sur Debian ?

  5. Synchronisation bidirectionnelle en temps réel d'une grande arborescence de fichiers entre deux serveurs Linux distants

Configuration de la synchronisation de fichiers Unison entre deux serveurs sur Debian 8 (Jessie)

Configuration de la synchronisation de fichiers Unison entre deux serveurs sur Debian 10 (Buster)

Comment trouver des fichiers dans Debian 10

Deux commandes pour trouver facilement des fichiers et des répertoires dans Debian 11

Installer Blender 3D sur Debian 10 (Buster)

Configurer Etherpad sur Debian