Luke
Luke

Reputation: 2063

sending script over ssh using ruby

I'm attempting to write a bash script in ruby that will start a Resque worker for one of my apps.

The command that I generate from the params given in the console looks like this...

command = "ssh user@#{@ip} 'cd /path/to/app; bundle exec rake resque:work QUEUE=#{@queue}&'"
`command`

The command is interpolated correctly and everything looks great. I'm asked to input the password for the ssh command and then nothing happens. I'm pretty sure my syntax is correct for making an ssh connection and running a line of code within that connection. ssh user@host 'execute command'

I've done a simpler command that only runs the mac say terminal command and that worked fine

command = "ssh user@#{@ip} 'say #{@queue}'"
`command`

I'm running the rake task in the background because I have used that line once inside ssh and it will only keep the worker alive if you run the process in the background.

Any thoughts? Thanks!

Upvotes: 1

Views: 971

Answers (2)

Luke
Luke

Reputation: 2063

I figured it out.

It was an rvm thing. I need to include . .bash_profile at the beginning of the scripts I wanted to run.

So... "ssh -f hostname '. .bash_profile && cd /path/to/app && bundle exec rake resque:work QUEUE=queue'" is what I needed to make it work.

Thanks for the help @Casper

Upvotes: 1

Casper
Casper

Reputation: 34308

Ssh won't exit the session until all processes that were launched by the command argument have finished. It doesn't matter if you run them in the background with &.

To get around this problem just use the -f switch:

-f  Requests ssh to go to background just before command execution.  This is
    useful if ssh is going to ask for passwords or passphrases, but the user
    wants it in the background.  This implies -n.  The recommended way to start
    X11 programs at a remote site is with something like ssh -f host xterm.

I.e.

"ssh -f user@#{@ip} '... bundle exec rake resque:work QUEUE=#{@queue}'"

EDIT

In fact looking more closely at the problem it seems ssh is just waiting for the remote side to close stdin and stdout. You can test it easily like this:

This hangs:

ssh localhost 'sleep 10 &'

This does not hang:

ssh localhost 'sleep 10 </dev/null >/dev/null &'

So I assume the last version is actually pretty closely equivalent to running with -f.

Upvotes: 0

Related Questions