Using Ruby and net-ssh, how do I authenticate using the key_data parameter with Net::SSH.start?

二次信任 提交于 2019-12-18 13:27:59

问题


I've read the net-ssh documentation, and I am still perplexed. I can authenticate manually (using ssh -i ...), and also by placing the key in a file and using the :keys parameter. However, I dont want to use the :keys parameter, I want to use the :key_data parameter. Can anyone give a working example? For some reason, directly feeding a string into :key_data is not working, and it gives the error: "Neither PUB key nor PRIV key:: nested asn1 error". Of course I googled that, and it basically tells me to make sure the key is in PEM format. And, of course it is. Any ideas? I can provide more detailed info if needed...


回答1:


I see this question in pretty old but I am going to throw the answer to you anyway just in case as I had the same issue and I just solved it.

In the following code note that the string containing the RSA key is not indented at all anywhere. The second line of the key does not have any leading space in it. TextMate put this there when I pasted the key in. I removed it and it worked like a charm.

#!/usr/bin/env ruby
require 'rubygems'
require 'net/ssh'

HOST = '172.20.0.31'
USER = 'root'

KEYS = [ "-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAqccvUza8FCinI4X8HSiXwIqQN6TGvcNBJnjPqGJxlstq1IfU
kFa3S9eJl+CBkyjfvJ5ggdLN0S2EuGWwc/bdE3LKOWX8F15tFP0=
-----END RSA PRIVATE KEY-----" ]

Net::SSH.start( HOST, USER, :key_data => KEYS, :keys_only => TRUE) do|ssh|
result = ssh.exec!('ls')
puts result
end



回答2:


I'm adding a little more info that I discovered myself after digging around the library...

Since 2.9.2, if your intention is to use only the key provided in key_data, you must also specify a blank set of keys before loading your key_data, or it will load some default keys.

In my case, one of those identity files it tried to load was passphrase-protected, so it asked me for my passphrase, though my intention was not to use that identify file at all.

Using the example above, in 2.9.2, you can get the same effect by doing something like this:

#!/usr/bin/env ruby
require 'rubygems'
require 'net/ssh'

HOST = '172.20.0.31'
USER = 'root'

KEYS = [ "-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAqccvUza8FCinI4X8HSiXwIqQN6TGvcNBJnjPqGJxlstq1IfU
kFa3S9eJl+CBkyjfvJ5ggdLN0S2EuGWwc/bdE3LKOWX8F15tFP0=
-----END RSA PRIVATE KEY-----" ]

Net::SSH.start( HOST, USER, :keys => [], :key_data => KEYS, :keys_only => TRUE) do|ssh|
result = ssh.exec!('ls')
puts result
end


来源:https://stackoverflow.com/questions/6905934/using-ruby-and-net-ssh-how-do-i-authenticate-using-the-key-data-parameter-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!