Outils pour utilisateurs

Outils du site


issue62:c_c

Before I begin with the actual article, I thought it might be useful to address a question I got via email. A reader was asking where best to place my wallpapers.sh script, and, in doing so, reminded me that I haven't ever explained how best to go about this. My approach is to store all my scripts in a single folder (either a folder called “scripts,” or, if I want to save some visual space in my home folder, I'll call it .bin or .scripts so the folder is hidden). Make sure any script you place here is executable (chmod +x), and that they specify in the first line which interpreter is required (#!/bin/bash, #!/usr/env python, etc.) - otherwise calling it will not work. Once that is done, you could create a symbolic link to the script in /usr/bin with sudo ln -s /path/to/script /usr/bin/script Avant de commencer cet article, proprement dit, je pense qu'il serait utile de répondre à une question que j'ai reçue par e-mail. Un lecteur demandait le meilleur endroit pour placer mon script wallpapers.sh et, ce faisant, il m'a rappelé que je n'avais jamais expliqué comment faire cela au mieux. Personnellement, je place tous mes scripts dans un dossier unique (p. ex. un dossier « scripts » , ou, si je veux gagner un peu de place « visuelle » dans mon dossier personnel, je l'appelle .bin ou .scripts et il est alors caché). Assurez-vous que chaque script mis ici soit exécutable (chmod +x) et que sa première ligne précise l'interpréteur requis (#!/bin/bash, #!/usr/env python, etc.) - sinon tout appel échouera. Cela terminé, vous pouvez créer un lien symbolique vers le script dans /usr/bin avec :

sudo ln -s /path/to/script /usr/bin/script

However, this can be complicated if you start removing scripts (it will leave broken links in your /usr/bin directory). Another method is to add the folder into your $PATH variable. This can be done with export PATH=$PATH:<folder>

Cependant, cela se complique si vous supprimez des scripts (cela laissera des liens brisés dans votre dossier /usr/bin). Une autre possibilité est d'ajouter le dossier à votre variable $PATH. Cela peut se faire avec :

export PATH=$PATH:<folder>

(replace folder with the actual path to the folder you created). To make it permanent, you can either place it in your .bashrc, your .xinitrc (if you start your interface with startx), or in any other script that gets called when you log in. I've had some hit-and-miss experiences with this, but generally /etc/environment works well. Since, however, the PATH is created in /etc/profile, you can also simply add the path to the scripts folder at the end of this path. I recommend avoiding any files in /etc/, and instead organize all your scripts within $HOME. This is due to the problems that can arise when creating system-wide settings using files that not all users can access. The problem is that anything in $HOME is restricted access wise to your user account. And now, on to the actual article.

(remplacez « folder » par le chemin vers le dossier que vous avez créé). Pour rendre cela permanent, vous pouvez le placer dans votre .bashrc, votre .xinitrc (si vous démarrez votre interface graphique avec startx), ou dans n'importe quel autre script appelé à votre ouverture de session. J'ai expérimenté cela avec plus ou moins de succès, mais habituellement /etc/environment fonctionne bien. Comme PATH est créé dans /etc/profile, vous pouvez aussi simplement ajouter le chemin du dossier des scripts à la fin de ce path. Je recommande d'éviter tout fichier dans /etc/ et plutôt d'organiser tous vos scripts dans $HOME. Cela est dû aux problèmes pouvant surgir lors de la création de configurations système qui utiliseraient des fichiers auxquels tous les utilisateurs n'ont pas accès. Tout ce qui se trouve dans $HOME est limité à votre compte utilisateur. Et maintenant, revenons au sujet de cet article.

The rest of my family has recently moved over to MacBooks for mobile workstations, and, for most of them, keeping files organized is fairly easy. For one of them, the MacBook is the only computer, and, for the other, it's a work machine where only company-related files need to be synchronized. However, for the latter person, whose PC runs both Arch Linux and Windows, it's a little more complicated. At first, I thought I'd use rsync in a custom script to synchronize the folders one after the other, but, since changes may be made on either machine, I needed a robust method to synchronize them (including deleted files). Rsync may be able to do this, but I have yet to get it working at 100%. As such, I began looking at unison again, which has resulted in me adopting it for my backup needs as well. Below, I describe my method for configuring Unison (which is available from the universe repository).

Le reste de ma famille est passé récemment sur des portables MacBooks et, pour la plupart d'entre eux, organiser leurs fichiers est assez simple. Pour l'un d'eux, le MacBook est son seul ordinateur et, pour l'autre, c'est une machine professionnelle où seulement les fichiers de la société doivent être synchronisés. Néanmoins, pour ce dernier, dont le PC est sous Arch Linux et Windows, c'est un peu plus compliqué. En premier, je pensais utiliser rsync dans un script propre pour synchroniser les dossiers les uns après les autres, mais, comme les modifications peuvent se faire sur l'une ou l'autre machine, il me fallait une méthode robuste pour les synchroniser (incluant les fichiers supprimés). Rsync pourrait peut-être le faire, mais je n'ai pas encore totalement réussi avec. C'est pourquoi je suis revenu vers Unison et l'ai finalement adopté aussi pour mes propres besoins de backup. Ci-dessous, je décris ma méthode pour configurer Unison (disponible dans le dépôt universe).

From the Unison manual “Unison is a file-synchronization tool for Unix and Windows. It allows two replicas of a collection of files and directories to be stored on different hosts (or different disks on the same host), modified separately, and then brought up to date by propagating the changes in each replica to the other.”

Selon le manuel d'Unison : « Unison est un utilitaire de synchronisation de fichiers pour Unix et Windows. Il permet deux copies identiques d'une collection de fichiers et de dossiers d'être stockées sur différents hôtes (ou différents disques sur le même hôte), modifiées séparément, et mises ensuite à jour par propagation des modifications d'une copie à l'autre.

To synchronize across multiple machines, the first thing you need to do is configure SSH on one of the machines (I did this on my mother’s PC, to minimize any possible security holes which would arise from a laptop with SSH enabled in public networks). It is also extremely important that you enable key-based logins on SSH. This is fairly easy with the following two commands: ssh-keygen -b 521 -t ecdsa -C“$(id -un)@$(hostname)-$(date –rfc-3339=date)”

Pour synchroniser entre différentes machines, la première étape nécessaire est de configurer SSH sur l'une des machines (j'ai choisi le PC de ma mère, pour réduire les risques éventuels de sécurité liés à un portable connecté à un réseau public avec SSH activé). Il est aussi très important d'activer la connexion SSH basée sur une clé. C'est assez simple avec les deux commandes suivantes :

ssh-keygen -b 521 -t ecdsa -C“$(id -un)@$(hostname)-$(date –rfc-3339=date)”

This creates the key. Follow the on-screen instructions. Keep in mind that entering a passphrase requires you to type this in when you use it – which defeats the point of a key-based login.

Cela va créer la clé. Suivez les instructions à l'écran. N'oubliez pas que si vous définissez une phrase de passe, vous devrez la saisir lors de l'utilisation de la clé - ce qui réduit l'intérêt d'une connexion basée sur clé.

scp ~/.ssh/id_ecdsa.pub username@remote-server.org:~/.ssh/authorized_keys This will copy the file into the authorized keys of the server, meaning that if you try ssh <IP>, without a username, it will automatically log you in using the key, without prompting for a password. Note: If your version of ssh doesn't support ecdsa, rsa keys are fine too.

scp ~/.ssh/id_ecdsa.pub username@remote-server.org:~/.ssh/authorized_keys

Copie le fichier dans le fichier des clés autorisées du serveur, ce qui veut dire que, si vous essayez ssh <IP>, sans nom d'utilisateur, cela vous connectera automatiquement en utilisant la clé, sans demander de mot de passe. Remarque : si votre version de ssh ne supporte pas ecdsa, les clés rsa sont bien aussi.

Now then, on to Unison. The easiest way to manage multiple synchronization folders is to create multiple profiles (.prf files). Since the options are all the same, I will cover only a single example. My Music sync profile looks like this: # Unison preferences label = Music sync root = /home/lswest/Music root = ssh:user@IPhome/lswest/Music/Hyperion/ fastcheck = true dontchmod = true ignore = Name *.ini ignore = Name *.jpg ignore = Name *.jpeg sshargs = -C

Et maintenant, passons à Unison. Le plus simple pour gérer des dossiers de synchronisation multiples est de créer plusieurs profils (fichiers .prf). Les options étant les mêmes, je vais expliquer un seul exemple. Mon profil de synchronisation musique ressemble à ceci :

# Unison preferences label = Music sync root = /home/lswest/Music root = ssh:user@IPhome/lswest/Music/Hyperion/ fastcheck = true dontchmod = true ignore = Name *.ini ignore = Name *.jpg ignore = Name *.jpeg sshargs = -C

From top to bottom, the settings do the following:

Du début à la fin, les paramètres font :

label – assigns the name of the profile, for the GUI's list of profiles.

label - définit le nom du profil, pour la liste des profils dans l'interface.

root – These are the sender/receiver (in that order). It shouldn't be possible to use more than 2 roots, though I haven't tested this.

root - Ce sont les source/destination (dans cet ordre). Il ne devrait pas être possible d'utiliser plus de 2 roots, bien que je ne l'aie pas testé.

fastcheck – I find that this reduces the search time immensely. It is supposed to be the default for Unix systems, but it doesn't hurt to be certain. The way this works is that it reads a file's modification times during the first pass, so it can ignore any files that weren't changed (meaning the modification times are the same as what was stored in the database). On the second pass. it generates a fingerprint. and compares it to the last contents to be synchronized.

fastcheck - Je trouve que cela réduit énormément le temps de recherche. C'est supposé être par défaut pour les systèmes Unix, mais cela ne fait pas de mal de préciser. La façon dont il procède : lecture de l'heure de modification des fichiers dans une première passe, ainsi il peut ignorer tous les fichiers non modifiés (heure de modification identique à celle de la base de données). Dans une seconde passe, il génère une signature et la compare au dernier contenu à synchroniser.

dontchmod – Unison tries to keep permissions the same, which is fine for syncs with Linux/Unix systems on either end, but for anything stored on NTFS (or with a Windows server), you will need to turn this off, to prevent dozens of permission warnings. Leaving this option isn't bad, as the permission settings simply fail, but it does slow down the transfers.

dontchmod - Unison essaie de conserver des permissions identiques, ce qui est bien lors de synchronisations entre systèmes Linux/Unix, mais pour n'importe quoi stocké sur NTFS (ou serveur Windows), vous devrez désactiver cette option, pour éviter des dizaines d'avertissements de permissions. Laisser cette option n'est pas mauvais, le paramétrage de permission ne fait qu'échouer, mais cela ralentit les transferts.

ignore – This option tells Unison what files to ignore. In my case, I ignore all the .ini files that Windows is so fond of creating (since my media is on an NTFS hard drive shared between Windows and Arch on my PC), and any of the cover art, since I use a different method in Linux.

ignore - Cette option indique à Unison quels fichiers ignorer. Dans mon cas, j'ignore tous les fichiers .ini que Windows prend un malin plaisir à créer (mon média étant un disque dur NTFS partagé entre Windows et Arch sur mon PC) et les pochettes, parce que j'utilise une autre méthode sous Linux.

sshargs – passes arguments to the ssh session. The option “-C” tells SSH to compress any of the information being sent, theoretically reducing transfer time per file (I haven't tested to see if this slows the entire process down, since the files need to be compressed, but for my rather large Music folder, it doesn't take too long to synchronize the changes these days).

sshargs - fournit les arguments à la session ssh. L'option « -C » indique à SSH de compresser les informations envoyées, ce qui réduit théoriquement le temps de transfert par fichier. (Je n'ai pas testé si cela ralentit tout le processus, puisque les fichiers doivent être compressés, mais pour mon dossier musique d'assez grande taille, cela ne prend pas trop de temps actuellement pour synchroniser les modifications.)

Keep in mind that the first run-through will take a while, since Unison has to assume every file is new.

N'oubliez pas que la première exécution prendra du temps, puisque Unison supposera que chaque fichier est nouveau.

The first few times you run Unison, I highly recommend manually checking the sync settings for each file that pops up (options are: right to left, left to right, skip), to make sure you're not losing/gaining any files you don't want. Once you're satisfied with how Unison is handling it, you can configure it to automatically accept non-conflicting changes. Do this by adding “auto = true” to the .prf file. You can also have Unison accept the non-conflicting changes, while skipping any conflicts with “batch = true”. Whether or not you can make this a completely automatic process, I'm not sure. However, you can minimize the input that is required using the above steps. To find out more about Unison, check the Further Reading section for a link to the user manual. If you want to simply mirror a folder in one direction (i.e. copy it from one machine to the next, without synchronizing), then I would still highly recommend rsync instead, due to the fact that it doesn't require any input when run properly. It's also extremely well documented in the manpage, making it quite easy to use. As a final note, I want to point out that both Unison and Rsync work for local folders too, meaning you can use it to create backups on a USB drive as well. If you decide to run these commands automatically on a schedule, I would recommend creating a script to first check if the USB drive is connected, or to check that you have the correct remote IP address (or can ping the router's IP). This is to avoid using resources to run a command that will simply fail. It also avoids opening SSH connections with computers that have the same IP but aren't your intended target, which could lead to problems down the line.

Les deux ou trois premières fois que vous exécuterez Unison, je recommande vivement de vérifier manuellement les paramètres de synchronisation pour chaque fichier qui apparaît (les options sont : de droite à gauche, de gauche à droite, ignorer), pour être certain de ne pas perdre ou gagner des fichiers non désirés. Une fois satisfait du traitement d'Unison, vous pouvez le configurer pour accepter les modifications non conflictuelles en ajoutant « auto = true » au fichier .prf. Unison peut aussi accepter les modifications non conflictuelles en ignorant les conflits avec « batch = true ». Je ne suis pas certain que vous puissiez rendre le processus complètement automatique. Cependant, vous pouvez diminuer les interventions en utilisant les options ci-dessus. Si vous voulez apprendre davantage sur Unison, la section « pour aller plus loin » ci-dessous reprend un lien vers le manuel utilisateur. Pour créer un miroir unidirectionnel de dossier (p. ex. copier d'une machine vers une autre, sans synchroniser), alors je recommanderais fortement rsync, qui ne nécessite pas d'intervention utilisateur quand il est exécuté correctement. Il est aussi très bien documenté (voir la manpage), ce qui le rend simple à utiliser. Enfin, j'aimerais souligner que Unison et Rsync fonctionnent aussi pour des dossiers locaux et vous pouvez les utiliser aussi pour réaliser des sauvegardes sur lecteurs USB. Si vous décidez d'exécuter ces commandes automatiquement dans un planificateur, je vous conseille de créer un script pour vérifier si le lecteur USB est branché ou pour vérifier si l'adresse IP distante est correcte (ou peut effectuer un ping sur l'IP du routeur). Ceci pour éviter d'utiliser des resources en exécutant une commande qui échouera. Et pour éviter d'ouvrir des connexions SSH avec des ordinateurs ayant la même IP, mais qui ne sont pas la cible voulue, ce qui peut entraîner des problèmes plus tard.

I hope at least some of you have found this interesting or helpful. I'm going to continue expanding my preferences files as I get more comfortable with Unison, and will mention any further tips I discover as time goes on. As always, if you have any questions, suggestions, or comments, you can reach me via email at lswest34@gmail.com. If you do decide to email me, please put “C&C”or “FCM” in the subject line, so that I don't overlook it.

J'espère qu'au moins certains d'entre vous avez trouvé cet article intéressant ou utile. En prenant de l'assurance avec Unison, je vais continuer à étendre mes fichiers de préférences et je mentionnerai toute astuce que je découvrirai au fil du temps. Comme toujours, si vous avez des questions, suggestions, ou remarques, vous pouvez me contacter par mail à lswest34@gmail.com. Si vous m'envoyez un courriel, indiquez « C&C » ou « FCM » en objet, ainsi je ne le négligerai pas.

Further Reading: Unison Manual: http://www.cis.upenn.edu/~bcpierce/unison/download/releases/stable/unison-manual.html#usingit Ubuntu Wiki page on SSH keys: https://help.ubuntu.com/community/SSH/OpenSSH/Keys

Pour aller plus loin :

Manuel d'Unison : http://www.cis.upenn.edu/~bcpierce/unison/download/releases/stable/unison-manual.html#usingit

Wiki Ubuntu, clés SSH : https://help.ubuntu.com/community/SSH/OpenSSH/Keys

issue62/c_c.txt · Dernière modification : 2012/08/24 15:38 de auntiee