2010-08-24 54 views
6

我在這裏有一個小問題:我嘗試使用私鑰將使用SCP和Ruby的文件上傳到服務器。代碼如下:我如何使用Ruby和私鑰來執行SCP?

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經驗非常有限。

+0

也許只是標註到scp命令? – rogerdpack 2010-08-24 13:13:23

+0

@folder如何定義?並請包括一個示例調用transfer_file方法 – 2010-08-24 16:25:36

+0

經過一番鬥爭,我們設法縮小了問題的環境配置問題。上面的代碼是正確的,對於繞過它的麻煩感到抱歉。對於那些感興趣的人來說,「另一方」有一些目錄訪問權限問題。 – fritzone 2010-09-10 07:15:11

回答

1

簡要介紹一下this文檔建議在您傳遞時它不接受ssh密鑰選項。但假設你是對的,我錯了那部分,

沒有看到你傳遞給transfer_file什麼價值和存儲在@folder中,我只能猜測,但假設他們都是文件對象,你可以不連接對象。你必須抓住他們的路徑屬性。您可能需要記錄這兩個變量的值以確保您獲得路徑。你也可以有更好的運氣使用Ruby "#{}"方法Concat的字符串參數,再次猜在這裏,但

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

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

1

似乎這成爲可能。根據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