简体   繁体   English

按需通过HTTP生成和流式传输命令的输出

[英]generate and stream output of a command over HTTP on demand

I'm doing a little Swiss Army Linuxing right now. 我现在正在做一些瑞士军Linuxing。 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. 我遇到了要运行命令,然后将其通过管道传送到仅用于该流的HTTP服务器的情况。 Here's the whole scenario: 这是整个场景:

  1. Start the server with a line like 用以下行启动服务器

     $ httpondemand parecord 

    Server does not start parecord right away. 服务器无法立即启动parecord。

  2. HTTP client connects. HTTP客户端连接。

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

    I CAN HAZ "/" ? 我可以危害“ /”吗?

  3. Server: Start parecord, get some output, reply "200 sigh , faaain,", send output. 服务器:启动parecord,得到一些输出,回复“200 叹息 ,faaain”,发送输出。

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 . 我找不到能做到这一点的工具,因此我最终写了一个工具,由于超出了本文档的范围,该工具被命名为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()

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

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