Created
November 5, 2019 19:00
-
-
Save blairanderson/b136bbfee5e80d9e48b6ad66010f9cd8 to your computer and use it in GitHub Desktop.
Ruby / Rails transfer files from SFTP to FTP folder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ftp_uri is calculated from environment variable and database encrypted account/password | |
class Transfer | |
def transfer | |
require 'net/sftp' | |
require 'net/ftp' | |
current_business = Business.find(business_id) | |
old_directory = "/orders/" | |
directory = "orders" | |
sftpuri = current_business.sftp_uri | |
uri = current_business.ftp_uri | |
Rails.logger.debug("SFTP_URI: #{sftpuri}") | |
Rails.logger.debug("URI: #{uri}") | |
ftp = Net::FTP.open(uri.host, uri.user, uri.password) | |
ftp.mkdir(directory) if !ftp.nlst.include?(directory) | |
puts 'making potential directory' | |
ftp.chdir(directory) | |
Net::SFTP.start(sftpuri.host, sftpuri.user, {:password => sftpuri.password, verbose: :debug}) do |sftp| | |
sftp.dir.entries(old_directory).each do |file| | |
backup = Tempfile.new([file.name.split(".").first, '.csv']) | |
begin | |
puts "Downloading #{file.name}" | |
sftp.download!("/#{old_directory}/#{file.name}", backup) | |
# backup.rewind | |
puts "Uploading #{file.name}" | |
ftp.putbinaryfile(backup.path, file.name) | |
ensure | |
backup.close! # Closes the file handle. If the file wasn't unlinked | |
# because #unlink failed, then this method will attempt | |
# to do so again. | |
end | |
end | |
end | |
puts ftp.nlst | |
ftp.close | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment