简体   繁体   English

Ruby'net / ssh'&基于bash cmd响应在ruby中使用逻辑

[英]Ruby 'net/ssh' & using logic in ruby based on bash cmd response

Using Ruby 'net/ssh' can I set a variable in ruby based on the output of a bash cmd in the target system log into? 我可以使用Ruby'net / ssh'来基于目标系统登录的bash cmd的输出在ruby中设置一个变量吗? The target system does not have ruby installed. 目标系统未安装ruby。 From my shell (has ruby obviously)... 从我的壳(显然是红宝石)...

For example (this works and returns the hostnames): 例如(这有效并返回主机名):

hosts = ['10.4.5.12', '10.4.5.18']
cmd = "/bin/hostname;"

hosts.each do |host|
    begin
         Net::SSH.start(host , username, :password => password, :paranoid=>false) $
         puts "\n#{host}\n"
         puts ssh.exec! cmd
         puts "\n"
    end
         rescue Timeout::Error
         puts "#{host} Timed out"
         rescue Errno::EHOSTUNREACH
         puts "#{host} Host unreachable"
         rescue Errno::ECONNREFUSED
         puts "#{host} Connection refused"
         rescue Net::SSH::AuthenticationFailed
         puts "#{host} Authentication failure"
    end
end

I want to use some additional logic in my script based on the output of 'cmd'. 我想基于“ cmd”的输出在脚本中使用一些其他逻辑。 If the hostname is x do this... I want to do this in ruby - not bash.. Make sense? 如果主机名是x,请执行此操作...我想用ruby进行此操作-而不是bash ..有意义吗? So in my ruby script -> test = output from cmd on target system (bash only) and then if test == x I'll run a second command. 因此,在我的ruby脚本中-> test =从目标系统上的cmd输出(仅限bash),然后如果test == x,我将运行第二条命令。

You can use syntax like this 您可以使用这样的语法

test = %x[ bash command ]

for example 例如

1.9.3-p448 :001 > command = %x[ echo "Hello world" ]
=> "Hello world\n" 

You can also check the return code of last command by calling 您还可以通过调用以下命令检查上一条命令的返回码

$?.exitstatus

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM