如何用Ruby和私钥做SCP?

时间:2010-08-24 09:29:22

标签: ruby key scp

我在这里遇到一个小问题:我尝试使用私钥将使用SCP和Ruby的文件上传到服务器。代码如下:

  def transfer_file(source_file, destination_file)
     $log.info("ScpDP: Key=#{@key}")
     Net::SCP.start(@host, @userName, :keys => @key ) do |scp|
       scp.upload!(source_file,@folder + destination_file, :ssh => @key)
     end
  end

但是有一些问题,而不是私钥,因为我们将它用于日常用途,并且我收到以下日志错误:

I, [2010-08-24T11:21:27.247847 #14310]  INFO -- : ScpDP: Key=/home/myself/.ssh/id_rsa
I, [2010-08-24T11:21:27.397971 #14310]  INFO -- : SCP did not finish successfully (1)   (Net::SCP::Error)
/usr/lib/ruby/gems/1.8/gems/net-scp-1.0.2/lib/net/scp.rb:351:in `start_command'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/channel.rb:585:in `call'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/channel.rb:585:in `do_close'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/session.rb:575:in `channel_close'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/session.rb:455:in `send'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/session.rb:455:in `dispatch_incoming_packets'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/session.rb:212:in `preprocess'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/session.rb:196:in `process'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/session.rb:160:in `loop'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/session.rb:160:in `loop_forever'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/session.rb:160:in `loop'
/usr/lib/ruby/gems/1.8/gems/net-ssh-2.0.11/lib/net/ssh/connection/session.rb:109:in `close'
/usr/lib/ruby/gems/1.8/gems/net-scp-1.0.2/lib/net/scp.rb:204:in `start'
/home/myself/work/server.rb:458:in `transfer_file'

请指出这里可能有什么问题?我现阶段的Ruby经验非常有限。

2 个答案:

答案 0 :(得分:1)

简要介绍this文档表明它不接受ssh密钥选项,因为您正在传递。但假设你是对的,那个部分我错了,

没有看到传递给transfer_file的值和@folder中存储的内容,我只能猜测,但假设它们都是文件对象,则无法连接对象。你必须抓住他们的路径属性。您可能希望记录这两个变量的值以确保获得路径。你可能还有更好的运气使用ruby "#{}"方法来连接字符串参数,再次在这里猜测但是

path = "#{@folder.path}/#{destination_file.path}" #=> "my_folder/destination_folder

scp.upload!(source_file,path, :ssh => @key)

答案 1 :(得分:1)

似乎现在可以了。根据{{​​3}},您可以使用Net :: SSH会话来执行scp命令。 结合net-scp docs关于在Ruby中使用私钥进行身份验证:

require 'net/ssh'
require 'net/scp'

ssh_private_keys = ['ssh-rsa AAAAB3NzaC1yc2EAAA', 'ssh-rsa AAAAB3NzaC1yc2EAAA']
Net::SSH.start(hostname, username, key_data: ssh_private_keys, keys_only: true) do |ssh|
  ssh.scp.upload!(source_file, destination_file)
end