2007-12-27
[Ruby]scpを使ったファイルの自動バックアップ
scpとcronでファイルを外部のサーバーへコピーしたかったのだけど、そういう場合はexpectとptyというのを使うといいらしい。
短いスクリプトなので貼っておく。
require 'pty'
require 'expect'
file1 = 'filename'
file2 = 'user@example.com:backup/'
passwd = 'pass'
cmd = "scp #{file1} #{file2}"
timeout = 30
puts "cmd: #{cmd}"
PTY.spawn(cmd) do |r, w|
r.expect(/password:/, timeout) { w.puts passwd }
puts r.read
end
サーバー側から~/backup/にファイルを引っ張ってくる場合は、次のような感じ。
file1 = 'user@example.com:filename' file2 = '~/backup/'