Using Ruby and SCP/SSH, how to determine if a file exists before uploading a copy

Zando picture Zando · Oct 26, 2009 · Viewed 8.2k times · Source

I'm uploading a file to a remote server using SCP, but what's the proper way of seeing if that file exists before doing so?

Answer

EmFi picture EmFi · Oct 26, 2009

You can't do this with scp. However you can do it with sftp. It would look something like this:

require 'net/sftp'

remote_path = "/path/to/remote/file"
Net::SFTP.start('host', 'username', :password => 'password') do |sftp|
  sftp.stat!(remote_path) do |response|
    unless response.ok?
    sftp.upload!("/path/to/local/file", remote_path)
  end
end