Public/Private Ruby Net::SFTP 的密钥验证

Public/Private key authentication for Ruby Net::SFTP

我找不到指定 SFTP 身份验证密钥的文档。

想要这样的东西:

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

Net::SFTP.start 将其 options 哈希直接传递给 Net::SSH.start,因此我们应该 look to its documentation。它列出了三个看起来相关的选项:

  • :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.

related question 的答案表明您可能需要使用全部三个:

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

如果您想使用来自 SOME_PRIVATE_KEY 环境变量的原始密钥数据,它应该如下所示:

Net::SFTP.start(ftp_host, user,
  key_data: [ ENV["SOME_PRIVATE_KEY"] ],
  keys: [],
  keys_only: true)