Stream console output through HTTP (with Ruby)

前端 未结 1 1147
再見小時候
再見小時候 2020-12-25 07:47

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

相关标签:
1条回答
  • 2020-12-25 08:48

    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
    

    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
    

    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.

    0 讨论(0)
提交回复
热议问题