rsync で バックアップ

何か楽ちんなバックアップ方法が無いものかと考えていたら、
お友達のYさんが rsync 使うといいよ。
と教えてくれました。
なので試しにやってみることにしました。

この方法は rsyncssh の公開鍵方式認証で秘密鍵パスフレーズを空にすることで
cron とかで動かせるというものです。

ssh の公開鍵と秘密鍵の仕組みは、
またいつか、書きましょう。
秘密鍵の流出が無ければ、セキュリティ上は安全です。

以下、手順をメモしますが、わかりやすいように ホスト名を
バックアップ元=src.com
バックアップ先=backup.com
とします。

まず、秘密鍵の作成ですが、バックアップ元で

root@src.com $ ssh-keygen -t rsa

として、秘密鍵を作成します。

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):Enter()
Enter same passphrase again:Enter()
Your identification has been saved in /root/.ssh.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
**:**:**:**:**:**:**:**:**:**:**:**:**:**:**:** root@src.com

てな感じで作成しました。

これを作成したときに同時にできた公開鍵をバックアップ先のサーバにコピーします。
scp コマンドを使うと FTP や USBメディア などを使わないでコピーできます。

root@src.com # scp /root/.ssh/id_rsa.pub backup.com:/home/user_name/.ssh/
id_rsa.pub                                                                                                   100%  402     0.4KB/s   00:00

次にバックアップ先サーバで公開鍵を authorized_keys に登録します。
単純に cat >> で追加でOK

user@backup.com $ cat /home/user_name/.ssh/id_rsa.pub >> /home/user_name/.ssh/authorized_keys

id_rsa.pub は両方のマシンからで削除しておきましょう

これで準備はOK、
バックアップ先に root で rsync したい場合は、

root@backup.com # vi /etc/ssh/sshd_config
PermitRootLogin noforced-commands-only

そして、rsync してみる
とりあえずテストディレクトリを作成

root@src.com # mkdir test
root@src.com # touch test/aaa
root@src.com # touch test/bbb
root@src.com # touch test/ccc
root@src.com # rsync -vaz --delete -e ssh /root/test user_name@backup.com:/home/user_name/backup/
building file list ... done
test/
test/aaa
test/bbb
test/ccc
sent 217 bytes  received 92 bytes  206.00 bytes/sec
total size is 0  speedup is 0.00


うんOK

cccを削除してみる

root@src.com # rm test/ccc
root@src.com # rsync -vaz --delete -e ssh /root/test user_name@backup.com:/home/user_name/backup/
building file list ... done
deleting test/ccc
test/
sent 90 bytes  received 26 bytes  232.00 bytes/sec
total size is 0  speedup is 0.00

うんOK

これは便利そうだから cron して使うことにしよう。
長年やってるけどこれ知らなかった自分が悲しい。