2

我正在尝试使用 ruby​​ 的 net ssh 远程运行命令。我需要输出以及退出代码。关于此主题还有其他 stackoverflow 线程,但已接受的解决方案不起作用。有些人建议使用 net-ssh-shell gem,但是当我尝试时,我得到一个错误,说这个包与我的 net-ssh 包的版本冲突......这是我所拥有的:

  Net::SSH.start(remote_ip, username,:keys => [ssh_key_path], :verbose => :debug) do |ssh|
    cmd = "blah bla"
    result = ssh.exec!(cmd)
    puts result
  end

它可以工作,但如果失败,它不会引发异常。我也尝试使用通道来检索退出代码,但它总是返回 0:

channel.on_request("exit-status") do |ch,data|
  exit_code = data.read_long
end

请帮帮我。我已经根据互联网上的错误信息尝试了几件事。

4

1 回答 1

3

如果您使用的是 Ruby 1.9+,我建议Open3.popen3

i, o, e, t = Open3.popen3("ssh ... remote_user@remote_host remote_command")
i.write ... # if your command needs input
output = o.read
error = e.read
status = t.value.exitstatus
于 2013-12-25T22:29:00.063 回答