简体   繁体   中英

generate and stream output of a command over HTTP on demand

I'm doing a little Swiss Army Linuxing right now. I've run into a situation where I want to run a command, then pipe it into an HTTP server, which serves just that stream. Here's the whole scenario:

  1. Start the server with a line like

     $ httpondemand parecord 

    Server does not start parecord right away.

  2. HTTP client connects.

     $ wget -O - http://server/ | mpv - 

    I CAN HAZ "/" ?

  3. Server: Start parecord, get some output, reply "200 sigh , faaain,", send output.

I am about to write the tool myself, but I thought I'd ask if there were anything already capable of this.

I couldn't find a tool that could do this, so I did end up writing one, which for reasons beyond the scope of this document, was named todd . I'd still rather use something that already exists, so this is not my ideal solution.

#!/usr/bin/env python

from socketserver import TCPServer
from http.server import BaseHTTPRequestHandler
import subprocess as sp
from sys import *

class ToddHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()

        # Do not start the command until after a connection has been made.
        p = sp.Popen(argv[1:], stdout=sp.PIPE)
        while True:
            data = p.stdout.read(1024)
            if len(data) == 0:
                break

            try:
                self.wfile.write(data)
            except BrokenPipeError:
                break
            except ConnectionResetError:
                break
        p.stdout.close()
        p.wait()  # Kill the zombie.

if len(argv) == 1:
    stderr.write('usage: todd command [arg1 arg2 ...]\n')

# Create the server.
server = TCPServer(('', 10000), ToddHandler)

# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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