【问题标题】:SSH Connections one after another, second one failsSSH连接一个接一个,第二个失败
【发布时间】:2013-08-03 00:02:45
【问题描述】:

我的代码需要我连接到一台服务器,rsync 到另一台服务器,然后连接到第二台服务器并在其上运行一堆命令。但毫无疑问,第二个 SSH 连接会引发 'do_open_failed': open failed (1) (Net::SSH::ChannelOpenFailed) 错误。我在这里做错了什么吗,有没有办法正确关闭第一个连接以使第二个连接连接?

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

【问题讨论】:

  • 另外,如果第一个连接不存在,第二个连接将运行良好。但显然我需要两者来做我正在做的事情。
  • 你试过用ssh.loop代替channel.wait吗?不知道有没有区别。
  • 另外,exec 不会阻止。在第二个起始块中,尝试改用exec!,或者让ssh 等待命令完成。
  • @JimLim 我如何使用ssh.loop 而不是channel.waitssh.loop{ channel } ?
  • 在第一次启动调用中,只需将channel.wait 替换为ssh.loop

标签: ruby net-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

【讨论】:

    猜你喜欢
    • 2019-06-04
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多