SFTP in Ruby
24 Apr 2025 - Gagan Shrestha
Working with SFTP in Ruby using net/sftp
SFTP (SSH File Transfer Protocol) is a secure way to transfer files over a network. In Ruby, the net-sftp
gem provides a simple and efficient way to interact with SFTP servers. In this post, we’ll explore how to use net/sftp
to upload, download, and manage files on a remote server.
Prerequisites
Before you begin, ensure you have the net-sftp
gem installed. You can install it via:
1
gem install net-sftp
You’ll also need the net-ssh
gem, as net-sftp
depends on it.
Basic SFTP Operations
1. Establishing a Connection
To start, require the library and establish an SFTP connection:
1
2
3
4
5
require 'net/sftp'
Net::SFTP.start('sftp.example.com', 'username', password: 'password') do |sftp|
# Your SFTP operations go here
end
You can also use key-based authentication:
1
2
3
Net::SFTP.start('sftp.example.com', 'username', keys: ['/path/to/private_key']) do |sftp|
# SFTP operations
end
2. Uploading a File
To upload a file to the remote server:
1
sftp.upload!('/local/path/file.txt', '/remote/path/file.txt')
For progress tracking during upload:
1
2
3
4
5
6
7
8
sftp.upload('/local/path/file.txt', '/remote/path/file.txt') do |event, uploader, *args|
case event
when :open then puts "Starting upload: #{args[0].local} -> #{args[0].remote}"
when :put then puts "Writing #{args[2].length} bytes to #{args[0].remote}"
when :close then puts "Finished upload"
when :finish then puts "All done!"
end
end
3. Downloading a File
To download a file from the remote server:
1
sftp.download!('/remote/path/file.txt', '/local/path/file.txt')
4. Listing Directory Contents
List files in a remote directory:
1
2
3
sftp.dir.foreach('/remote/path') do |entry|
puts entry.name
end
5. Creating and Deleting Directories
Create a new directory:
1
sftp.mkdir!('/remote/path/new_directory')
Delete a directory (must be empty):
1
sftp.rmdir!('/remote/path/empty_directory')
6. Deleting Files
Remove a file:
1
sftp.remove!('/remote/path/file.txt')
Error Handling
Always handle potential errors:
1
2
3
4
5
6
7
8
9
begin
Net::SFTP.start('sftp.example.com', 'username', password: 'password') do |sftp|
sftp.upload!('/local/file.txt', '/remote/file.txt')
end
rescue Net::SFTP::Exception => e
puts "SFTP Error: #{e.message}"
rescue Net::SSH::Exception => e
puts "SSH Error: #{e.message}"
end
Conclusion
The net-sftp
gem provides a powerful yet simple interface for interacting with SFTP servers in Ruby. Whether you’re uploading, downloading, or managing files, it handles most common use cases with ease. For more advanced features, check out the official documentation.
Happy secure file transferring!