【问题标题】:ruby running commands on a remote machineruby 在远程机器上运行命令
【发布时间】:2013-12-26 06:29:00
【问题描述】:

我正在尝试使用 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

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

【问题讨论】:

    标签: ruby net-ssh


    【解决方案1】:

    如果您使用的是 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
    

    【讨论】:

    • 太好了。我将它与 ssh 密钥一起使用,还需要添加 require 'open3' 并且它运行良好。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    相关资源
    最近更新 更多