Key-based authentication with net-sftp in Ruby

I want to be able to use SFTP to log in to multiple servers and download specific files to help debug problems as they arise. Although we could use the client, we wanted to start automating the process to simplify 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 that we need a password. Ideally, I want to use public key authentication, but I don't see any link to this in the documentation or on the Internet - is this possible?

I would prefer not to use chilkat.

thanks

+3
source share
2 answers

( SSH), Net:: SSH, SFTP.

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

Net:: SCP

Net::SSH.start('localhost', 'user', keys: ['keys/my_key'] ) do |ssh|
  ssh.scp.download("/local/file.txt", "/remote/file.txt")
end
+9

Source: https://habr.com/ru/post/1722322/


All Articles