使用ruby通过ssh发送脚本

时间:2013-01-14 17:35:17

标签: ruby bash ssh resque

我正在尝试在ruby中编写一个bash脚本,它将为我的某个应用程序启动一个Resque worker。

我从控制台中给出的参数生成的命令看起来像这样......

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

命令插入正确,一切看起来都很棒。我被要求输入ssh命令的密码,然后没有任何反应。我非常确定我的语法对于建立ssh连接并在该连接中运行一行代码是正确的。 ssh user@host 'execute command'

我做了一个更简单的命令,只运行mac say终端命令,并且工作正常

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

我正在后台运行rake任务,因为我在ssh中使用了一行,如果你在后台运行该进程,它只会让工作者保持活着状态。

有什么想法?谢谢!

2 个答案:

答案 0 :(得分:1)

我明白了。

这是一件事。我需要在我想要运行的脚本的开头包含. .bash_profile

所以... 我需要"ssh -f hostname '. .bash_profile && cd /path/to/app && bundle exec rake resque:work QUEUE=queue'"才能使其发挥作用。

感谢@Casper的帮助

答案 1 :(得分:0)

在命令参数启动的所有进程完成之前,Ssh不会退出会话。如果您使用&在后​​台运行它们并不重要。

要解决此问题,只需使用-f开关:

-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.

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

修改

事实上,仔细查看问题似乎ssh只是等待远程端关闭stdinstdout。您可以像这样轻松地进行测试:

这挂起:

ssh localhost 'sleep 10 &'

这不会挂起:

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

所以我认为最后一个版本实际上与使用-f非常接近。