如何使用Ruby的Net :: SSH库获取退出状态? [英] How to get exit status with Ruby's Net::SSH library?
问题描述
我有一段代码,只是尝试在远程服务器上执行脚本,如果脚本失败,我想进行跟进,想象一下:
I have a snippet of code, simply trying to execute a script on a remote server, in the event that it fails, I'd like to make a follow-up call, imagine this:
require 'rubygems'
require 'net/ssh'
require 'etc'
server = 'localhost'
Net::SSH.start(server, Etc.getlogin) do |ssh|
puts (ssh.exec("true") ? 'Exit Success' : "Exit Failure")
puts (ssh.exec("false") ? 'Exit Success' : "Exit Failure")
end
我期望(忽略在我为人为的示例中打印的stdout和stderr)-但是第一行应该以0
退出,我希望Ruby会以false
的形式出现并显示"Exit Failure"(确定,所以逻辑是错误的,三元数需要翻转)-但是第二行应该以相反的状态退出,而事实并非如此.
I would expect (ignoring that stdout and stderr are printed in my contrived example) - but first line should exit with 0
which I would expect Ruby would interperate as false
and display "Exit Failure" (sure, so the logic is wrong, the ternary needs to be flipped) - but the second line should exit with the opposite status, and it doesn't.
我什至找不到文档中有关如何执行此操作的信息,我有点担心自己做错了吗?!
I can't even find anything in the documentation about how to do this, and I'm a little worried that I might be doing it wrong?!
推荐答案
我发现使用Net :: SSH运行进程的以下方式更为有用.它为您提供了不同的stdout
和stderr
,exit code
和exit signal
.
I find the following way of running processes with Net::SSH much more useful. It provides you with distinct stdout
and stderr
, exit code
and exit signal
.
require 'rubygems'
require 'net/ssh'
require 'etc'
server = 'localhost'
def ssh_exec!(ssh, command)
stdout_data = ""
stderr_data = ""
exit_code = nil
exit_signal = nil
ssh.open_channel do |channel|
channel.exec(command) do |ch, success|
unless success
abort "FAILED: couldn't execute command (ssh.channel.exec)"
end
channel.on_data do |ch,data|
stdout_data+=data
end
channel.on_extended_data do |ch,type,data|
stderr_data+=data
end
channel.on_request("exit-status") do |ch,data|
exit_code = data.read_long
end
channel.on_request("exit-signal") do |ch, data|
exit_signal = data.read_long
end
end
end
ssh.loop
[stdout_data, stderr_data, exit_code, exit_signal]
end
Net::SSH.start(server, Etc.getlogin) do |ssh|
puts ssh_exec!(ssh, "true").inspect
# => ["", "", 0, nil]
puts ssh_exec!(ssh, "false").inspect
# => ["", "", 1, nil]
end
希望这会有所帮助.
这篇关于如何使用Ruby的Net :: SSH库获取退出状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!