Приручаем rsync в Mac OS X
Большая часть пользователей компьютеров Apple пользуются встроенным в Mac OS X решением для резервного копирования своих данных — Time Machine (TM). Я, однако, принадлежу к меньшинству, которое не пользуется «машиной времени».
Дело в том, что мне нужен бэкап по сети, а по сети Time Machine умеет копировать данные либо на Time Capsule, либо на общую папку, расшаренную на компьютере под управлением Mac OS X Leopard (и выше). Time Capsule я покупать не собираюсь, потому что она мне не внушает доверия, а другого мака в доме нет. Существуют различные хаки, при помощи которых можно заставить TM записывать резервные копии в любую сетевую папку, но у всех этих хаков есть побочные эффекты, бороться с которыми как-то не хочется. Поэтому — rsync, rsync и ещё раз rsync. Однако Apple не была бы Apple, если бы в духе заботы о пользователе не разложила на этом пути грабли, с которыми мы сейчас и будем бороться 🙂
Грабли заключаются в том, что в комплекте с Mac OS X поставляется очень странная версия rsync. Давайте посмотрим на неё внимательнее при помощи команды rsync —version:
rsync version 2.6.9 protocol version 29
Capabilities: 64-bit files, socketpairs, hard links, symlinks, batchfiles,
inplace, IPv6, 64-bit system inums, 64-bit internal inums
Во-первых, она очень древняя (текущая версия — 3.0.7 — отличается усовершенствованным алгоритмом сравнения файлов и работает быстрее). Во-вторых, эппловский rsync собран с поддержкой метаданных файловой системы HFS+ и поддерживает специальный ключ -E для сохранения этих самых метаданных… но при этом на другом конце должна быть такая же «модифицированная» версия rsync. То есть «получателем» резервной копии опять же может выступать только компьютер с Mac OS X (Tiger или выше).
Не беда, эта проблема по большей части решается. Для начала мы скомпилируем на маке последнюю версию rsync (у вас должен быть установлен Xcode).
Загружаем исходные тексты:
cd
/Desktop
curl -O rsync.samba.org/ftp/rsync/src/rsync-3.0.7.tar.gz
tar -xzvf rsync-3.0.7.tar.gz
rm rsync-3.0.6.tar.gz
curl -O rsync.samba.org/ftp/rsync/src/rsync-patches-3.0.7.tar.gz
tar -xzvf rsync-patches-3.0.7.tar.gz
rm rsync-patches-3.0.7.tar.gz
cd rsync-3.0.7
Применяем релевантные патчи:
patch -p1
Теперь собираем:
./prepare-source
./configure
make
sudo make install
Проверяем, что у нас получилось:
melchior:
pavel$ /usr/local/bin/rsync —version
rsync version 3.0.7 protocol version 30
Copyright (C) 1996-2009 by Andrew Tridgell, Wayne Davison, and others.
Web site: rsync.samba.org
Capabilities:
64-bit files, 64-bit inums, 64-bit timestamps, 64-bit long ints,
socketpairs, hardlinks, symlinks, IPv6, batchfiles, inplace,
append, ACLs, xattrs, no iconv, symtimes, file-flags
Теперь необходимо скомпилировать rsync на Linux-машине, которая будет использоваться для бэкапа, с применением патча fileflags, но БЕЗ патча crtimes! В Ubuntu 9.10 для этого надо сначала установить «средства производства»:
sudo apt-get install build-essential
sudo apt-get build-dep rsync
Делаем тестовый прогон:
/usr/local/bin/rsync -aHAXxzv —protect-args —fake-super —rsync-path=»/usr/local/bin/rsync»
Осталась только одна проблема: при попытке сделать бэкап на ext3-раздел, rsync ругнётся на то, что расширенные атрибуты файлов не помещаются в отведённое под них пространство. Для решения этой проблемы я отформатировал диск, на который производится бэкап, в XFS.
Основной недостаток данного метода заключается в том, что он не сохраняет атрибуты времени создания и модификации файла. Впрочем, для меня это некритично, потому что мне удалённый бэкап нужен не для создания загрузочной копии системного диска, а для обеспечения сохранности дорогих моему сердцу документов.
rsync хорош и тем, что можно написать скрипт и регулярно запускать его cron’ом. В этом случае резервное копирование будет осуществляться без вашего вмешательства. Но это уже тема для отдельной записи…
Источник
rsync Backups on a Mac
rsync is already installed on your Mac OS X system. With no software to install and no previous experience, you can configure simple, elegant backups from your mac in the true UNIX tradition.
Remember — we will write your commands or scripts for you so don’t hesitate to ask.
Overview — Four Steps
1. You (or rsync.net Support) will create a backup script that backs up the Folders that are important on that system.
2. Then you will create an SSH key for secure, automated backups to our service.
3. Then you will run this script once to completion — that will be the initial backup.
4. After the initial backup is completed, you will schedule that very same script to run at the time(s) of your choosing.
The rsync Script
Your Mac OS X system has one or more directories that are valuable to you. This list usually starts with /Users, which contains all of the user home directories. Depending on your system and what you have installed, you may also include /etc or /opt.
Whatever the list is, simply email that list of directories you want backed up to rsync.net Support and ask them to create an rsync backup script for your mac.
That script will look something like this:
All we are doing in that script is backing up /Users. We insert a «BEGIN» and «END» line into a new file on your system named «/var/log/backup.log», which might be helpful for troubleshooting in the future. We also «caffeinate» the rsync command so that the backup will run to completion even if your system is scheduled to sleep while the backup is still running.
Again, just email rsync.net Support your list of directories and we will create this script for you
Create SSH Keys for Automated Backups
Make sure you are logged in as the user who will do the backups, and then open the Terminal Application and run:
When you hit ‘enter’ the output will be:
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/username/.ssh/id_rsa): Just hit enter to accept the default
Enter passphrase (empty for no passphrase): Yes, hit enter for an EMPTY passphrase
Enter same passphrase again: Hit enter again to CONFIRM the EMPTY passphrase
Your identification has been saved in /Users/username/.ssh/id_rsa.
Your public key has been saved in /Users/username/.ssh/id_rsa.pub.
The key fingerprint is:
a7:a0:38:5c:8d:99:33:99:ea:54:b3:e3:3c:6b:a7:9f username@null-2.local
Now you have an SSH keypair for the user you are currently logged in as.
Upload your newly created public key using this command:
(of course, inserting your username and rsync.net hostname in place of «user@rsync.net»)
Now quickly test that your key works:
You should not be asked for a password when executing the above ‘ls’ command over ssh.
Running the Script
Once you have downloaded the script, you can run it for the very first time by simply double-clicking it in your Downloads directory.
When you run the script for the first time, it may take some time — perhaps even several hours — to complete. This is because you are uploading all of your data for the very first time to your rsync.net account.
After the initial upload, however, your backups will complete in much less time. Only the changes between backups will be sent after this initial upload is finished.
We do not schedule the backups at all until the initial backup has completed — otherwise, you might begin your next automated backup before the first one successfully finished.
Scheduling Your Backups
Do NOT schedule your backups until AFTER your initial backup completes — see «Running the Script», above.
There are three ways to schedule your rsync backups: Point and Click Simple with iCal, Power User Precision with launchd/plist, or «Get Off My Lawn» with crontab.
If you have never done this before, use the Point and Click Simple method, with iCal.
If you know what you are doing and you have a system that sometimes sleeps, use the launchd/plist method.
If we really should just get off your lawn, use the crontab method (this is our preferred method).
Point and Click, Simple Scheduling, with Calendar/iCal
Open up Calendar (your local Calendar — not your Google or sync’d Calendar) and choose «New Event» from the File menu.
The new event can be titled anything you like — for instance «rsync.net cloud backup».
You should select the start time you would like the backups to run at — perhaps something like 1am or 2am. The duration of the event is not important — you can leave it at the default of one hour.
Set the «repeat» setting to what you like, but presumably this is a daily backup so you should probably set it to «daily».
You will need to further modify the event as follows so that your new backup script is run at the time of the event:
a. under ‘alert:’ select ‘Custom. ‘
b. The first dropdown should be changed from ‘Message’ to ‘Open file’
c. It will then reveal a new dropdown named ‘Calendar’, click that and choose ‘Other. ‘, then.
d. find and select the script you downloaded (rsyncnet_backup.sh)
e. Change ‘minutes before’ to ‘At time of event’
f. Click OK
Now your Calendar event has been created and will run at the time of your choosing.
NOTE: If your mac is asleep when the event occurs, it will NOT run, and will simply run when the computer is woken up. If you would like the event to run at the proper time regardless of whether the system is asleep or not then you need to enter System Preferences, open «Energy Saver», click the «Schedule» button in the lower right, and check the «start up or wake» box, then choose a time 10 minutes AFTER (yes, after) your job is scheduled to run. Now the system will wake up and see that a job was scheduled to run and will run it immediately.
Power User Precision with launchd/plist
First, generate a launchd plist for yourself using this link — just fill in the schedule (ex: min=5, hour=0, day of month=* would setup a job that runs daily at 5min after midnight local time), name of the job, path to your script and extras as you require. At the very least, you’ll need to configure something in the schedule. Now click the green «Create .plist» button. You may also simply download a stock plist here.
Now, scroll down to «Manual Install» and paste in those three commands that have been generated for you, BUT add two lines to change the ownership and permissions of the file:
/Library/LaunchAgents .
curl -o
/Library/LaunchAgents/.
chmod o-w
launchctl load -w .
If you think your mac might be asleep when the scheduled time for this backup arises, you can alter your power settings to wake the computer up 10 minutes AFTER (yes, after) your job is scheduled to run:
If you want to power on a powered off system, you’d use this instead:
Get Off My Lawn — I’m Using crontab
This is the method we prefer. Yes, crontab did NOT work well in Snow Leopard and possibly Lion, and yes, Apple has declared it obsolete and unsupported. However, we have found that in recent OS X releases, cron and crontab work exactly as you would expect them to.
The only problem is that cron jobs (unlike launchd plist jobs) do not reliably run themselves after a power off / sleep event. This means that we cannot recommend crontab scheduling on a mac unless it is a machine that is up and running at all hours and does not ever sleep. If you have a system that could be powered off periodically, or go to sleep, you should (unfortunately) use the launchd/plist method, above.
Источник
MacBook: синхронизируем данные через rsync
Rsync я пользуюсь уже давно — для синхронизации данных между Windows системами. Для этого есть порт cwRsync, который очень просто устанавливается и настраивается. Итак, у нас имеется:
1. Удаленная система, на которой расшарена нужная директория
2. Локальная система, куда мы хотим записать изменения с удаленной системы
Синхронизация односторонняя, подразумевается, что мы возим с собой ноутбук, на который нужно время от времени скопировать файлы с десктопа и наоборот. Двусторонняя синхронизация с разрешением конфликтов — более сложный вопрос и лучше до этого не доводить 🙂
В Windows rsync видит все диски как «/cygdrive/ «, например «/cygdrive/c». Простой скрипт, выполняемый на ноутбуке и синхронизирующий директорию «work» с десктопом:
net use t: \\my-desktop\c
rsync -rltObv —delete —backup-dir=/cygdrive/c/backup /cygdrive/t/work /cygdrive/c
net use t: /delete
Для понимания процесса рассмотрим каждую опцию:
-r — рекурсивность, синхронизируются все директории внутри «work»
-l — можно опустить, если внутри директории нет ссылок (symbolic links), опция копирует ссылки в виде ссылок, а не файлов
-t — очень важная опция. При ее включении rsync смотрит время последней модификации файла и перезаписывает файл только в том случае, если оно отличается от времени файла на удаленном компьютере. Если ее не включить, rsync будет всегда перезаписывать все файлы, на что уйдет значительно больше времени.
-O — не применять «-t» к директориям. Если не включить эту опцию, новые директории на локальной системе не будут создаваться.
-v — выдавать на экран сообщения, какие файлы записались или удалились
-b — делать бекап всех перезаписанных или удаленных файлов
—backup-dir — директория, в которой создаются бекапы
—delete — удалять те файлы, которых нет на удаленной системе
В Windows эта схема уже давно отработана и без проблем служит мне много лет. Однако в Mac OS есть некоторые нюансы.
Если под Windows мы всегда синхронизировали между собой 2 системы с NTFS, то здесь одна из систем это FAT32 или exFAT (рассматривается случай, когда на машине стоит еще Windows и раздел с документами общий для обеих ОС). При подключении к Mac OS FAT, файлы на котором были записаны другой ОС, все файлы по умолчанию имеют статус «locked», т.е. «read only». Их нельзя перезаписать даже с админскими правами. Однако этот флажок можно снять. Делается это так:
chflags -R nouchg *
Теперь мы можем быть уверены, что rsync без проблем перезапишет наши файлы, а ненужные удалит. rsync входит в состав той FreeBSD, на базе которой сделана Mac OS, но стоит там очень старая версия. Поэтому ставим новую версию из MacPorts:
sudo port install rsync
MacPorts помещает исполняемые файлы в /opts/local/bin, соответственно путь к правильной версии rsync будет /opts/local/bin/rsync.
Новая версия rsync значительно быстрее выполняет стадию сравнения двух директорий.
Однако я столкнулся с проблемой: около половины файлов почему-то перезаписывались, несмотря на идентичность. Причина оказалась очень простая: в FAT немного другой формат представления времени файла и время может отличаться на +-1 секунду, т.е. секунды в FAT это всегда четное число. Для устранения этого безобразия в rsync есть опция modify-window, которая устанавливает допустимый разброс времени. Достаточно добавить:
—modify-window=1
и проблема решена. Если синхронизация происходит на HFS — этой проблемы нет.
И еще одна небольшая проблемка — русские и другие нелатинские буквы отображаются HEX-значениями. На саму синхронизацию это не влияет, но выглядит некрасиво. Для этого у rsync есть опция «8» — показывать полные 8-битные символы.
Итак, вот пример скрипта под Mac OS, синхронизирующий папку на разделе FAT с папокй с Windows компьютера:
#!/bin/bash
mount -t smbfs //user:password@my-desktop/c /Volumes/my-desktop-c
cd /Volumes/FAT
chflags -R nouchg *
/opts/local/bin/rsync -rltObv8 —delete —backup-dir=/Volumes/FAT/backup —modify-window=1 /Volumes/my-desktop-c/work /Volumes/FAT
umount /Volumes/my-desktop-c
Конечно директория /Volumes/my-desktop-c должна быть заранее создана, чтобы в нее подмонтировался удаленный диск.
Источник