I want to be able to use SFTP to login into a number of servers and download certain files to help debug issues as and when they arise. While we could use a client, we wanted to start automating the process to streamline everything.
My first attempt looks something like this:
def download(files_to_download, destination_directory)
Net::SFTP.start(@server, @username, :password => @password) do |sftp|
files_to_download.each do |f|
local_path = File.join(destination_directory, File.basename(f))
sftp.download!(f, local_path)
end
end
end
While this works, it means we need the password. Ideally, I want to be using public key authentication however I can't see any reference to this in the documentation or online - is this possible?
I would prefer not to use chilkat.
Thanks
If you want to directly specify the key (or other SSH options) you can first open a Net::SSH connection, and then do SFTP operations from there.
Net::SSH.start("localhost", "user", keys: ['keys/my_key']) do |ssh|
ssh.sftp.upload!("/local/file.tgz", "/remote/file.tgz")
ssh.exec! "cd /some/path && tar xf /remote/file.tgz && rm /remote/file.tgz"
end
This also works for Net::SCP
Net::SSH.start('localhost', 'user', keys: ['keys/my_key'] ) do |ssh|
ssh.scp.download("/local/file.txt", "/remote/file.txt")
end