代码之家  ›  专栏  ›  技术社区  ›  Ferenc Deak

如何使用Ruby和私钥执行SCP?

  •  6
  • Ferenc Deak  · 技术社区  · 15 年前

    这里有一个小问题:我尝试使用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 回复  |  直到 10 年前
        1
  •  1
  •   Jed Schneider    15 年前

    简要地看一下 this 文档表明它不接受ssh密钥选项,因为您正在传递。但假设你是对的,而我在这方面是错的,

    在看不到传递给传输文件的值和存储在@folder中的值的情况下,我只能猜测,但假设它们都是文件对象,则无法连接这些对象。您必须获取它们的路径属性。您可能需要记录这两个变量的值,以确保获得路径。使用红宝石也会有更好的运气。 "#{}" 方法来concat字符串参数,这里再次猜测,但是

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

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

        2
  •  1
  •   Community Mohan Dere    9 年前

    看来这是可能的。根据 net-scp docs ,可以使用net::ssh会话执行 scp 命令。 结合 this answer 关于使用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
    
    推荐文章