简体   繁体   English

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

[英]Ruby net/ssh is not running bash commands in background

I am having a hard time running bash commands in background from a Ruby script.我很难从 Ruby 脚本在后台运行 bash 命令。

For this question, I am using a simplified example.对于这个问题,我使用了一个简化的示例。

This is how commands are working as expected when I run them from PuTTY.这就是我从 PuTTY 运行命令时命令按预期工作的方式。

running basch commands in background (click to see the picture, because StackOverlow is not allowing me to show pictures yet)在后台运行 basch 命令(点击查看图片,因为 StackOverlow 还不允许我显示图片)

Now, I try to replicate this from Ruby, using this little script shown below:现在,我尝试使用如下所示的小脚本从 Ruby 复制它:

ruby script (click to see the picture, because StackOverlow is not allowing me to show pictures yet) ruby 脚本(点击查看图片,因为 StackOverlow 还不允许我显示图片)

This is the outout I get when I run such a Ruby script:这是我运行这样一个 Ruby 脚本时得到的结果:

script output (click to see the picture, because StackOverlow is not allowing me to show pictures yet)脚本输出(点击查看图片,因为 StackOverlow 还不允许我显示图片)

For your analysis, here is the transcription of the Ruby script:为了您的分析,这里是 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)

You need to redirect both stdout and stderr somewhere else than the terminal, otherwise exec!您需要将 stdout 和 stderr 都重定向到终端以外的其他地方,否则exec! will hang waiting for process output.将挂起等待进程输出。

This is the simplest solution I found:这是我找到的最简单的解决方案:

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

&> redirects both stdin and stderr at the same time. &>同时重定向标准输入和标准错误。 If you want to redirect the output for logging, you can do so separately if you like:如果要重定向输出以进行日志记录,可以根据需要单独执行此操作:

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

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

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