Julie Rain
Julie Rain

Reputation: 61

Upload files from local directory to SFTP using Ruby

For some reason SFTP upload in Ruby (copy files from local directory to SFTP server) doesn't seem to work. I'm currently using Ruby 2.5.3. I would really appreciate any ideas :

My code below:

require 'net/ssh'
require 'net/sftp'

server = 'sftp.secure.net'
username = '123456'
password = "Mypassword*"
uid = '123456'

files = Dir.entries(outdir)
Net::SFTP.start(server, username, :password=>password) do |sftp|
  for filename in files
     #puts files
      puts "Browsing files..." 
      puts "File: #{filename}" 
     #puts new_filename

####### replacing , for | ########

     if /#{uid}_test_[0-9]{8}_[0-9]{8}.txt$/ =~ filename
     file = "#{outdir}\\#{filename}"
     puts "SFTPing #{file}"
     sftp.upload(file) 
     puts "SFTP Complete for file #{file}"
     puts "Cleanup"
     puts "Deleting #{file}."
     File.delete(file)
     puts "Files were deleted." 
     end
  end
puts "Closing SFTP connection..." 
sftp.close
puts "SFTP connection closed."
end

Upvotes: 2

Views: 3900

Answers (2)

Adwin
Adwin

Reputation: 119

SFTP is an entirely different protocol based on the network protocol SSH (Secure Shell).

Read SFTP vs. FTPS: The Key Differences .

Use gem net-sftp.

Ex:

require "net/sftp"

Net::SFTP.start("host", "username", :password: "password") do |sftp|
    #from your system(local)
    sftp.upload!("/path/to/local", "/path/to/remote")
    
    # through URL
    open(your_file_url) do |file_data|
        sftp.upload!(file_data, /path/to/remote)
    end
end

Upvotes: 1

Julie Rain
Julie Rain

Reputation: 61

Thank you Kennycoc! That upload! was definitely helpful. Also, sftp.close() should be deleted for sftp. The SFTP connection automatically close. This is needed for FTP I found out, but not for SFTP.

Thanks!

Finalized Version:

files = Dir.entries(outdir)
Net::SFTP.start(hostname, username, :password=>password) do |sftp|
for filename in files
     #puts files
      puts "Browsing files..." 
      puts "File: #{filename}" 
     #puts new_filename

####### replacing , for | ########

     if /#{uid}_test_[0-9]{8}_[0-9]{8}.txt$/ =~ filename
     file = "#{outdir}\\#{filename}"
     puts "SFTPing #{file}"
     sftp.upload!(file) 
     puts "SFTP Complete for file #{file}"
     puts "Cleanup"
     puts "Deleting #{file}."
     File.delete(file)
     puts "Files were deleted." 
     end
end
#puts "Closing SFTP connection..." 
#sftp.close()
puts "SFTP connection closed."
end

Upvotes: 1

Related Questions