2013-08-02 92 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 
相关问题