8

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
Blair Anderson
  • 19,463
  • 8
  • 77
  • 114

1 Answers1

16

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)
Jordan Running
  • 102,619
  • 17
  • 182
  • 182