Public/Private key authentication for Ruby Net::SFTP
Asked Answered
D

1

12

I am having trouble finding documentation for specifying a key for SFTP authentication.

Would like to have something like:

export SOME_PRIVATE_KEY="$(cat tmp/some-certs/privatekey.pem)"

# then somewhere in the code
private_key = OpenSSL::PKey::RSA.new(ENV['SOME_PRIVATE_KEY'])

Net::SFTP.start(ftp_host, user, key: private_key) do |sftp|
  sftp.dir.entries('/path/to/folder').each do |remote_file|
     # ...
  end
end
Dilantin answered 6/6, 2017 at 20:52 Comment(0)
B
21

Net::SFTP.start passes its options hash directly to Net::SSH.start, so we should look to its documentation. It lists three options that look relevant:

  • :keys => an array of file names of private keys to use for publickey and hostbased authentication
  • :key_data => an array of strings, with each element of the array being a raw private key in PEM format.
  • :keys_only => set to true to use only private keys from keys and key_data parameters, even if ssh-agent offers more identities. This option is intended for situations where ssh-agent offers many different identites.

The answer to a related question suggests that you may need to use all three:

Net::SFTP.start(ftp_host, user,
  key_data: [],
  keys: "tmp/some-certs/privatekey.pem",
  keys_only: true)

If you want to use the raw key data from the SOME_PRIVATE_KEY environment variable instead, it ought to look like this:

Net::SFTP.start(ftp_host, user,
  key_data: [ ENV["SOME_PRIVATE_KEY"] ],
  keys: [],
  keys_only: true)
Bluegrass answered 6/6, 2017 at 21:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.