The following post shows how to connect to an SFTP server in Ruby on Rails and work with remote files using Ruby code. SFTP is a widely used secure protocol for file transfer, and once the connection is in place, you can list files, upload files, and download files from the remote server.

In the example below, we'll use the net-sftp gem to connect to an SFTP server, parse credentials from an environment variable, and then carry out the core file operations many applications need. By the end of the post, you'll have a working Ruby SFTP example that covers connection, file listing, uploads, downloads, and a full script.


Requirements for using SFTP in Ruby on Rails

First things first, preparation. The net-sftp gem is required in order to connect to and interact with an SFTP server in Ruby on Rails.

gem install net-sftp

Or create a `Gemfile` file and declare your dependencies in it:

gem 'net-sftp'

Then run:

bundle install

Once that's done, the application has what it needs to open an SFTP connection and start working with remote files.


Connecting to SFTP in Ruby on Rails

In this example, we'll be using an environment variable named SFTPTOGO_URL that contains all the information required to connect to an SFTP server in URI format: sftp://user:password@host.

The variable is parsed with URI.parse to extract the different URI parts, and the remote server’s host key is verified by default using ~/.ssh/known_hosts. Once the connection is established, the SFTP client object is assigned to the instance variable @sftp_client.

This part of the code handles the connection lifecycle, including connect and disconnect methods, and wraps the underlying SSH session so the SFTP session can be reused cleanly.

require 'net/sftp'
require 'uri'

class SFTPClient
  def initialize(host, user, password)
    @host = host
    @user = user
    @password = password
  end

  def connect
    sftp_client.connect!
  rescue Net::SSH::RuntimeError
    puts "Failed to connect to #{@host}"
  end

  def disconnect
    sftp_client.close_channel
    ssh_session.close
  end


  def sftp_client
    @sftp_client ||= Net::SFTP::Session.new(ssh_session)
  end

  private

  def ssh_session
    @ssh_session ||= Net::SSH.start(@host, @user, @password)
  end

end

sftptogo_url = ENV['SFTPTOGO_URL']
begin
  uri = URI.parse(sftptogo_url)
rescue URI::InvalidURIError
  puts 'Bad SFTPTOGO_URL'
end

sftp = SFTPClient.new(uri.host, uri.user, password: uri.password)
sftp.connect


# disconnect
sftp.disconnect

Listing files on an SFTP server with Ruby

Now that we have a working connection, we can use it to list files on the remote SFTP server.

This is done by traversing the @sftp_client.dir.foreach method, which returns objects corresponding to the files found in the path argument. In this example, the wrapper function prints the files found in the remote path.

This is also a useful first check when testing a new SFTP connection. If the file listing works, the session, credentials, and target path are usually in good shape.

def list_files(remote_path)
  @sftp_client.dir.foreach(remote_path) do |entry|
    puts entry.longname
  end
end

Uploading a file to SFTP in Ruby on Rails

The next step is to upload a file.

Use the @sftp_client object’s upload function and pass the path to the local file and the remote path where the file should end up after the upload completes. A function call would look like this: @sftp_client.upload!("./local.txt", "./remote.txt")

This gives you a direct way to move files from the local system to the remote SFTP server from inside a Ruby application.

def upload_file(local_path, remote_path)
  @sftp_client.upload!(local_path, remote_path)
  puts "Uploaded #{local_path}"
end

Downloading a file from SFTP in Ruby on Rails

As we finalize the process, we just need to download our files.

Use the @sftp_client object’s download function and pass the path to the remote file and the local path in which to store the downloaded file. You would call the function like so: @sftp_client.download!("./remote.txt", "./download.txt")

This is the other side of the same workflow and is useful for applications that need to retrieve reports, partner files, exports, or other remote data.

def download_file(remote_path, local_path)
  @sftp_client.download!(remote_path, local_path)
  puts "Downloaded #{remote_path}"
end

The whole Ruby on Rails SFTP example

All done. If you would like to run the entire program from start to finish, copy the following code and save it as main.rb:

require 'net/sftp'
require 'uri'

class SFTPClient
  def initialize(host, user, password)
    @host = host
    @user = user
    @password = password
  end

  def connect
    sftp_client.connect!
  rescue Net::SSH::RuntimeError
    puts "Failed to connect to #{@host}"
  end

  def disconnect
    sftp_client.close_channel
    ssh_session.close
  end

  def upload_file(local_path, remote_path)
    @sftp_client.upload!(local_path, remote_path)
    puts "Uploaded #{local_path}"
  end

  def download_file(remote_path, local_path)
    @sftp_client.download!(remote_path, local_path)
    puts "Downloaded #{remote_path}"
  end

  def list_files(remote_path)
    @sftp_client.dir.foreach(remote_path) do |entry|
      puts entry.longname
    end
  end

  def sftp_client
    @sftp_client ||= Net::SFTP::Session.new(ssh_session)
  end

  private

  def ssh_session
    @ssh_session ||= Net::SSH.start(@host, @user, @password)
  end
end

sftptogo_url = ENV['SFTPTOGO_URL']
begin
  uri = URI.parse(sftptogo_url)
rescue URI::InvalidURIError
  puts 'Bad SFTPTOGO_URL'
end

sftp = SFTPClient.new(uri.host, uri.user, password: uri.password)
sftp.connect

# list files in directory
sftp.list_files('/path/to/remote')

# upload files
sftp.upload_file('/path/to/local', '/path/to/remote')

# download files
sftp.download_file('/path/to/remote', '/path/to/local')


# disconnect
sftp.disconnect

Finally, run it using the command:

ruby main.rb


Where this Ruby SFTP example can help

This example is useful if you want to:

  • Connect to an SFTP server from Ruby on Rails
  • List files on a remote SFTP server
  • Upload files from a Ruby application
  • Download files from a remote SFTP server
  • Start building file transfer automation in Ruby

It is a practical starting point for application workflows that need secure server-to-server file movement without unnecessary complexity.


Congratulations on connecting to SFTP using Ruby on Rails!

From here, you can build on the same pattern for larger application workflows, partner file exchanges, scheduled jobs, or internal automation. The core pieces are already in place: connect, list files, upload, download, and disconnect cleanly.

Check out more code samples on Github. Explore SFTP automation to reduce human error and streamline workflows.


Frequently asked questions

How do I connect to an SFTP server in Ruby on Rails?

You can connect to an SFTP server in a Ruby on Rails app by using the net-sftp gem and creating an SFTP session over an SSH connection. In this example, the connection details are loaded from an environment variable and then used to open the session.

What gem do I need for SFTP in Ruby?

This example uses the net-sftp gem. It provides SFTP operations such as listing files, uploading files, and downloading files from Ruby.

Can I list files on an SFTP server with Ruby?

Yes. In this example, file listing is done by traversing the SFTP directory entries for a remote path and printing each entry.

How do I upload a file to SFTP in Ruby on Rails?

You can upload a file by calling the SFTP client’s upload method and passing the local file path and the remote destination path. In this example, the synchronous upload! method is used.

How do I download a file from SFTP in Ruby on Rails?

You can download a file by calling the SFTP client’s download method and passing the remote file path and the local destination path where the file should be saved. In this example, the synchronous download! method is used.

What does SFTPTOGO_URL do in this Ruby SFTP example?

In this example, SFTPTOGO_URL stores the SFTP connection details in URI format. The code parses it to extract the host, username, and password needed for the connection. It is part of this example’s setup, not a requirement of Ruby on Rails or the net-sftp gem itself.