通过 HTTP 流控制台输出(使用 Ruby) [英] Stream console output through HTTP (with Ruby)

查看:43
本文介绍了通过 HTTP 流控制台输出(使用 Ruby)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试远程运行一些命令,但无法通过 SSH 连接到机器.我想要做的是设置一个 Sinatra 应用程序,它运行一些特定的命令并通过 HTTP 流式传输输出.

I am trying to run some commands remotely and SSH'ing in to the machine is not an option. What I am trying to do is setup a Sinatra app that runs some specific commands and streams the output through HTTP.

示例操作如下所示:

get "/log" do
  `tail -f some.log`
end

1 据我所知,我需要使用 Unicorn(或 Mongrel),因为 Thin 不支持流数据2 我想我需要管道通过某种 IO ruby​​ 对象输出的命令

1 As far as I've read, I need to use Unicorn (or Mongrel) because Thin does not support streaming data 2 I think I need to pipe the commands output through some kind of IO ruby object

我几乎知道怎么做(1)但不知道怎么实现(2).

I almost know how to do (1) but have no idea how to achieve (2).

推荐答案

如果您在同步服务器上(即 Mongrel、Unicorn、not Thin),您可以只返回一个 IO 对象:

If you're on a synchronous server (i.e. Mongrel, Unicorn, not Thin), you can just return an IO object:

require 'sinatra'

get '/log' do
  content_type :txt
  IO.popen('tail -f some.log')
end

如果这不起作用(例如,如果您使用的是 Thin),您可以使用新的流 API:

If that doesn't work (if you're on Thin, for instance), you can use the new streaming API:

require 'sinatra'

get '/log' do
  content_type :txt
  IO.popen('tail -f some.log') do |io|
    stream do |out|
      io.each { |s| out << s }
    end
  end
end

您还可以使用 bcat gem,如果它包含 ANSI 颜色代码,它将为您的输出着色:

You can also use the bcat gem, which will colorize your output, if it contains ANSI color codes:

require 'sinatra'
require 'bcat'

get '/log' do
  command = %[tail -f some.log]
  bcat = Bcat.new(command, :command => true)
  bcat.to_app.call(env)
end

注意:对于无限运行的进程,如果有人关闭连接,您必须自己杀死进程.使用第一个解决方案,一些服务器可能会为您处理.

Note: For infinitely running process you'll have to take care of killing the process yourself if someone closes the connection. With the first solution some servers might take care of that for you.

这篇关于通过 HTTP 流控制台输出(使用 Ruby)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆