ExpandedVenture / ConnectionSphere

Simple Service to Start Prospecting Online
0 stars 0 forks source link

Ruby net/ssh is not running bash commands in background #295

Closed leandrosardi closed 2 years ago

leandrosardi commented 2 years ago

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.

image

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

image

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

image

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)
leandrosardi commented 2 years ago

Here is the ruby code that I need to get working:

        logger.logs "kill... "
        output = host.ssh.exec!("pkill xterm; pkill chrome; pkill ruby;").strip
        logger.logf "done (#{output.strip})"

        logger.logs "get display code... "
        display = host.ssh.exec!("ps -ef |grep Xauthor | grep -v grep | nawk '{print $9}'").strip
        logger.logf "done (#{display.strip})"

        s = "DISPLAY=#{display};export DISPLAY;/bin/bash --login -c \"/home/bots/run.worker.prod.sh\" &"
        logger.logs "run (#{s})... "
        stdout = host.ssh.exec!(s)
        logger.logf "done (#{stdout.strip})"
leandrosardi commented 2 years ago

https://stackoverflow.com/questions/72249949/ruby-net-ssh-is-not-running-bash-commands-in-background

leandrosardi commented 2 years ago

Here is the fix:

s = "bash --login -c 'sleep 600' >/dev/null 2>&1 &"
print "run (#{s})... "
stdout = ssh.exec!(s)
puts "done (#{stdout.strip})"