简体   繁体   English

从Rails应用程序使用SSH进行远程执行命令

[英]Remote Execute Command using SSH from Rails Application

I have a Rails Application from which I will call one Ruby Definition in the controller, like this. 我有一个Rails应用程序,从中我将在控制器中调用一个Ruby定义,就像这样。

ssh root@host "uptime" >> /tmp/output

When I doing this, only the /tmp/output is created but not the content. 当我这样做时,仅创建/ tmp / output,而不创建内容。 When I running the same from simple Ruby script its working fine. 当我从简单的Ruby脚本运行它时,它的工作正常。

my controller definition 我的控制器定义

  def chefclient1
    `ssh root@host "uptime" >> /tmp/output`
    @time = Time.now
  end

my view 我的观点

= link_to('Start uptime', host_chefclient1_path)

You can use net-ssh gem to access remote host via ssh fo a ruby app. 您可以使用net-ssh gem通过Ruby应用程序中的ssh访问远程主机。 Set your environment up to: 将环境设置为:

HOSTNAME = 'host'
USER = 'root'
PASS = 'password'

Add to your_helper.rb: something like: 添加到your_helper.rb中

def chefclient1
   result = nil
   Net::SSH.start( ENV[ 'HOSTNAME' ], ENV[ 'USER' ], :password => ENV[ 'PASS' ] ) do| ssh |
      result = ssh.exec! 'uptime'
      puts result
   end

   File.open( '/tmp/output', 'w' ) {| f | f.puts result }
end

And use the helper method as you with from a view. 并从视图中使用辅助方法。

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

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