2013-08-02 117 views
1

我有代碼要求我連接到一臺服務器,rsync連接到另一臺服務器,然後連接到第二臺服務器並在其上運行一堆命令。但是沒有失敗,第二個SSH連接會引發'do_open_failed': open failed (1) (Net::SSH::ChannelOpenFailed)錯誤。我在這裏做錯了什麼,有沒有辦法正確關閉第一個連接,使第二個連接?SSH連接一個接一個,第二個連接失敗

Net::SSH.start(self.from_creds['host'], self.from_creds['user'], :password => self.from_creds['password']) do |ssh| 
    channel = ssh.open_channel do |ch| 
    ch.exec "/usr/bin/rsync -e ssh -varuzP --exclude=sys-export --delete #{self.from_creds['filepath']}/#{self.client_id}/ #{self.scp_to}/#{new_client_id}" do |ch, success| 
     raise "could not execute command" unless success 

     # "on_data" is called when the process writes something to stdout 
     ch.on_data do |c, data| 
     $stdout.print data 
     end 

     # "on_extended_data" is called when the process writes something to stderr 
     ch.on_extended_data do |c, type, data| 
     $stderr.print data 
     end 

     ch.on_close { puts "done!" } 
    end 
    end 
    channel.wait 
end 
Net::SSH.start(self.to_creds['host'], self.to_creds['user'], :password => self.to_creds['password']) do |ssh1| 
    # Do some other stuff here 
    tmp_path = "#{self.to_creds['filepath']}/tmp/#{Time.now.to_i}" 
    ssh1.exec "mkdir -p #{tmp_path}" 
    ssh1.exec "cd #{self.to_creds['filepath']}/#{new_client_id}" 
end 
+0

而且,第二連接將代表第一個是不存在運行正常。但很顯然,我需要兩者都在做什麼。 – Magicmarkker

+0

您是否嘗試過使用'ssh.loop'而不是'channel.wait'?我不知道是否有區別。 –

+0

另外,'exec'不會阻止。在第二個啓動塊中,請嘗試使用'exec!',或者使'ssh'等待命令完成。 –

回答

1

根據文檔,exec不阻止。改用exec!來代替。

Net::SSH.start(self.to_creds['host'], self.to_creds['user'], :password => self.to_creds['password']) do |ssh1| 
    # Do some other stuff here 
    tmp_path = "#{self.to_creds['filepath']}/tmp/#{Time.now.to_i}" 
    ssh1.exec! "mkdir -p #{tmp_path}" 
    ssh1.exec! "cd #{self.to_creds['filepath']}/#{new_client_id}" 
end 

或者,

Net::SSH.start(self.to_creds['host'], self.to_creds['user'], :password => self.to_creds['password']) do |ssh1| 
    # Do some other stuff here 
    tmp_path = "#{self.to_creds['filepath']}/tmp/#{Time.now.to_i}" 
    ssh1.exec "mkdir -p #{tmp_path}" 
    ssh1.exec "cd #{self.to_creds['filepath']}/#{new_client_id}" 
    ssh1.loop 
end 
相關問題