rsync
ファイルの同期を取るためのコマンドにrsyncというのがある。
それをRubyのコードから利用する方法を紹介します。
ruby-rsync
exampleは以下の通り
rsync.rb
require "rsync"
Rsync.run("/path/to/src", "/path/to/dest") do |result|
if result.success?
result.changes.each do |change|
puts "#{change.filename} (#{change.summary})"
end
else
puts result.error
end
end
ただしこれだと同一サーバ内での同期になってしまうので、タイトルにある通り別サーバ間でのファイル同期を行う方法が以下のとおり。
runメソッドの引数にsshユーザとドメインとファイルパスを文字列として渡してやることで別サーバ間でのファイル同期が行われる。
ただし、パスワード入力が必要な場合は手動で入力しなくてはならないため、パスワード認証ではなく鍵認証でsshできるように設定が必要
rsync.rb
require "rsync"
# Rsync.run("コピー元", "コピー先")
# 第1引数説明 sshユーザ名@サーバドメイン or IP:ファイルパス
Rsync.run("vagrant@192.168.33.10:/tmp/vagrant10/sync_doc", "/tmp/sync1/sync_doc") do |result|
if result.success?
result.changes.each do |change|
puts "#{change.filename} (#{change.summary})"
end
else
puts result.error
end
end