rubybashsshnet-ssh

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.

For this question, I am using a simplified example.

This is how commands are working as expected when I run them from PuTTY.

running basch commands in background (click to see the picture, because StackOverlow is not allowing me to show pictures yet)

Now, I try to replicate this from Ruby, using this little script shown below:

ruby script (click to see the picture, because StackOverlow is not allowing me to show pictures yet)

This is the outout I get when I run such a Ruby script:

script output (click to see the picture, because StackOverlow is not allowing me to show pictures yet)

For your analysis, here is the transcription of the Ruby script:

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)

Solution

  • You need to redirect both stdout and stderr somewhere else than the terminal, otherwise 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 &")