Поиск по сайту:

Настройка синхронизации файлов Unison между двумя серверами в Debian 8 (Джесси)


Это руководство существует для этих версий ОС

  • Debian 6 (сжать)

На этой странице

  1. 1 Предварительное примечание
  2. 2 Установка Unison
  3. 3 Создание пары закрытый/открытый ключ на server1
  4. 4 Бег в унисон
  5. 5 Создание задания Cron для Unison
  6. 6 Тестовый унисон
  7. 7 ссылок

В этом руководстве показано, как настроить синхронизацию файлов между двумя серверами Debian 8 с помощью Unison. Unison — это инструмент синхронизации файлов, похожий на rsync, большая разница в том, что он отслеживает/синхронизирует изменения в обоих направлениях, т. е. файлы, измененные на сервере 1, будут реплицированы на сервер 2 и наоборот.

1 Предварительное примечание

В этом руководстве я буду использовать следующие два сервера Debian:

  • server1.example.com с IP-адресом 192.168.1.101.
  • server2.example.com с IP-адресом 192.168.1.102.

Я хочу синхронизировать каталог /var/www между двумя серверами. В этом руководстве я буду запускать Unison от имени пользователя root, чтобы у Unison было достаточно разрешений для синхронизации разрешений пользователя и группы.

Все команды в этом руководстве выполняются от имени пользователя root. Войдите на оба сервера в оболочке как root и начните с шага 2 \Установка Unison\.

2 Установка Унисона

Unison должен быть установлен на server1 и server2; поскольку мы подключаемся с сервера 1 к серверу 2 с помощью SSH, нам также потребуются пакеты SSH, и я установлю редактор nano для редактирования файлов в оболочке. Этого можно достичь следующим образом:

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

3 Создание пары закрытый/открытый ключ на server1

Теперь мы создаем пару закрытый/открытый ключ на server1.example.com:

ssh-keygen -t dsa

[электронная почта защищена]:~#

Важно, чтобы вы не вводили кодовую фразу, иначе зеркалирование не будет работать без участия человека, поэтому просто нажмите ENTER!

Далее копируем наш публичный ключ на server2.example.com:

ssh-copy-id -i $HOME/.ssh/id_dsa.pub 
# ssh-copy-id -i $HOME/.ssh/id_dsa.pub 
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
's password: <-- server2 root password
Number of key(s) added: 1
Now try logging into the machine, with: "ssh ''"
and check to make sure that only the key(s) you wanted were added.

Теперь проверьте на server2, правильно ли передан открытый ключ server1:

cat $HOME/.ssh/authorized_keys

4 Бегущий унисон

Теперь мы можем запустить Unison в первый раз, чтобы синхронизировать каталог /var/www на обоих серверах. На сервере1 запустите:

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

Вывод будет похож на этот — возможно, вам придется ответить на несколько вопросов, поскольку Unison запускается впервые:

:/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)

Проверьте каталог /var/www на серверах server1 и server2, и вы обнаружите, что теперь они синхронизированы.

Конечно, мы не хотим запускать Unison в интерактивном режиме, поэтому мы можем создать файл настроек (/root/.unison/default.prf), содержащий все настройки, которые в противном случае нам пришлось бы указывать в командной строке:

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

Комментарии должны сделать файл понятным, за исключением директив пути. Если вы не укажете никаких директив пути, то будут синхронизированы каталоги в корневых директивах. Если вы указываете директивы пути, то пути относятся к корневому пути (например, root=/var/www и path=current преобразуются в /var/www/current), и будут синхронизированы только эти подкаталоги, а не весь указанный каталог. в корневой директиве.

Вы можете узнать больше о доступных параметрах, взглянув на справочную страницу Unisons:

man unison

Теперь, когда мы поместили все настройки в файл настроек (особенно директивы root (и, возможно, пути), мы можем запустить Unison без каких-либо аргументов:

unison

5 Создание задания Cron для Unison

Мы хотим автоматизировать синхронизацию, поэтому создаем для нее задание cron на server1.example.com:

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

Это будет запускать Unison каждые 5 минут; настройте его в соответствии с вашими потребностями (см.

man 5 crontab

). Я использую здесь полный путь к унисону (/usr/bin/unison), просто чтобы убедиться, что cron знает, где найти унисон. Ваше местоположение унисона может отличаться. Бег

which unison

узнать, где твоя.

6 тестовый унисон

Теперь я проверю двухстороннюю синхронизацию Unison, чтобы убедиться, что установка полностью работает.

Выполните следующую команду на server1, чтобы создать тестовый файл с содержимым \Test 1\:

Сервер1

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

Теперь подождите не менее 5 минут (так как мы создали cronjob, который запускается раз в 5 минут). Затем запустите на server2:

cat /var/www/test.txt

для отображения содержимого файла test.txt на экране. Вывод должен быть похож на этот снимок экрана.

Теперь запустите эту команду на server2, которая обновит содержимое нашего тестового файла до \Test 2\:

Сервер2

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

И подождите не менее 5 минут. Затем запустите команду cat на server1:

Сервер1

cat /var/www/test.txt

Вывод должен быть таким, как показано на скриншоте.

7 ссылки

  • Унисон: http://www.cis.upenn.edu/~bcpierce/unison/
  • Debian: http://www.debian.org/