开发者

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

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


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


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".


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜