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

I am uploading a file to a remote server using SCP, but what is the correct way to see if this file exists before then?

+2


source to share


3 answers


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

The best way to redirect would be to set 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 will get an "allowed" response, which can be subject to minor interpretations (eg, have directory permissions changed?). This is one of the drawbacks of this method).



How do you set permissions for a remote file? The easiest way to do this is to install them in a local file and then save them on boot. Ruby Net :: SCP README says that it can indeed "preserve file attributes across different transfers".

+2


source


You cannot do this with scp. However, you can do it with sftp. It will 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

      

+9


source


This will definitely resolve your question and provide additional information. http://ruby.about.com/od/ssh/ss/netscp.htm

-1


source







All Articles