Created
February 6, 2017 21:36
-
-
Save zas/9e3c8333c26a9240443b813a2ee81215 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/python | |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer | |
from subprocess import Popen, PIPE | |
import argparse | |
import json | |
import os | |
import shlex | |
import signal | |
import sys | |
DEFAULT_PORT = 8080 | |
def sigterm_handler(_signo, _stack_frame): | |
# Raises SystemExit(0): | |
sys.exit(0) | |
def get_exitcode_stdout_stderr(cmd, shell=False): | |
""" | |
Execute the external command and get its exitcode, stdout and stderr. | |
""" | |
args = shlex.split(cmd) | |
proc = Popen(args, stdout=PIPE, stderr=PIPE, shell=shell, | |
env=dict(os.environ, LC_ALL='C')) | |
out, err = proc.communicate() | |
exitcode = proc.returncode | |
return exitcode, out, err | |
class myHandler(BaseHTTPRequestHandler): | |
# Handler for the GET requests | |
def do_GET(self): | |
status = 500 | |
body = {} | |
cmd = "ls -1z" | |
exitcode, out, err = get_exitcode_stdout_stderr(cmd) | |
if exitcode == 0: | |
# TODO: module/class for command and its parser | |
# https://github.com/influxdata/telegraf/tree/master/plugins/inputs/httpjson | |
body["output"] = out | |
status = 200 | |
else: | |
body["error"] = { | |
"exitcode": exitcode, | |
"out": out, | |
"err": err, | |
"cmd": cmd | |
} | |
self.send_response(status) | |
self.send_header('Content-type', 'application/json') | |
self.end_headers() | |
self.wfile.write(json.dumps(body)) | |
signal.signal(signal.SIGTERM, sigterm_handler) | |
parser = argparse.ArgumentParser(description='Very simple http server') | |
parser.add_argument('-p', '--port', help='TCP port to listen on (default: %d)' % | |
DEFAULT_PORT, type=int, | |
default=DEFAULT_PORT) | |
args = parser.parse_args() | |
port = args.port | |
try: | |
# Create a web server and define the handler to manage the | |
# incoming request | |
server = HTTPServer(('', port), myHandler) | |
print('Listening on port %d' % port) | |
# Wait forever for incoming htto requests | |
server.serve_forever() | |
except KeyboardInterrupt: | |
print('Keyboard interrupt...') | |
finally: | |
server.socket.close() | |
print("Goodbye.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment