Created
February 5, 2012 02:14
-
-
Save postmodern/1742022 to your computer and use it in GitHub Desktop.
A WEBrick shell server with async output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'webrick' | |
class Server < WEBrick::HTTPServlet::AbstractServlet | |
def self.start(port,host=nil) | |
server = WEBrick::HTTPServer.new(:Host => host, :Port => port) | |
server.mount '/', self | |
trap('INT') { server.shutdown } | |
server.start | |
end | |
def self.shell | |
@@shell ||= begin | |
io = IO.popen(ENV['SHELL'],'r+') | |
io.extend AsyncRead | |
io | |
end | |
end | |
def do_POST(request,response) | |
self.class.shell.puts request.query['cmd'] | |
response.status = 200 | |
end | |
def do_GET(request,response) | |
response.status = 200 | |
response.chunked = true | |
response.body = self.class.shell | |
end | |
module AsyncRead | |
def read(length) | |
begin | |
read_nonblock(length) | |
rescue IO::WaitReadable | |
IO.select([self]) | |
retry | |
end | |
end | |
end | |
end | |
Server.start 1337 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment