Question

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?

Was it helpful?

Solution

Beware check-then-upload: this is not atomic and may lead to race conditions (or TOCTOU vulnerabilities).

A better way forwards might be to set the file permissions on the uploaded file so that it is not writable (400 or 444 or similar on UNIX-like systems), then any subsequent uploads to the same filename will simply fail. (You'll get "permission denied" back which may be subject to a little interpretation (eg did the upload directory permissions change?). This is one downside to this method).

How do you set permissions on the remote file? The simplest way to do that is to set them on the local file and then preserve them when you do the upload. Ruby's Net::SCP README says that it can indeed "preserve file attributes across transfers".

OTHER TIPS

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

This definitely solves your question and will give extra information as well. http://ruby.about.com/od/ssh/ss/netscp.htm

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top