Ruby net/ssh没有在后台运行bash命令



我很难从Ruby脚本在后台运行bash命令。

对于这个问题,我使用了一个简化的例子。

当我从PuTTY中运行命令时,命令是如何按预期工作的。

在后台运行bash命令(点击查看图片,因为StackOverlow还不允许我显示图片)

现在,我试着从Ruby中复制这个,使用下面的小脚本:

ruby脚本(点击查看图片,因为StackOverlow还不允许我显示图片)

这是我运行这样一个Ruby脚本时得到的输出:

脚本输出(点击查看图片,因为StackOverlow还不允许我显示图片)

为了便于分析,下面是Ruby脚本的转录:

require 'net/ssh'
net_remote_ip = '74.****122'
ssh_username = 'bots'
ssh_password = 'San*****'
get_ssh_port = '22'
ssh = Net::SSH.start(net_remote_ip, ssh_username, :password => ssh_password, :port => get_ssh_port)
s = "bash --login -c 'sleep 600' &"
print "run (#{s})... "
stdout = ssh.exec!(s)
puts "done (#{stdout.strip})"
ssh.close
exit(0)

您需要将标准输出和标准错误重定向到终端以外的其他地方,否则exec!将挂起等待进程输出

这是我找到的最简单的解决方案:

ssh.exec!("sleep 600 &> /dev/null &")

&>同时重定向stdin和stderr。如果您想重定向输出以进行日志记录,您可以根据需要单独执行:

ssh.exec!("command 2> error.log > output.log &")

最新更新