SpaceSaver2000
SpaceSaver2000

Reputation: 100

Is there a way to start a new command prompt window from a get request in python HTTP server that doesn't interrupt the main thread?

This is my first time posting and I'm running into quite the issue. Unlike most people who want their code to execute a command and wait for it to finish, I want to launch it in a new terminal window that's completely separate. This is using a Python HTTP server and I just cannot get it to run without holding up the main thread until the terminal window is closed. I've tries subprocess.call, subprocess.Popen, subprocess.run, os.system, and none of them have worked. I'm open to any suggestions. Here's the code:

start.bat

python trigger.py "0.0.0.0" "8080" "EatThisHackers!!!!" "python requesthandler.py"

trigger.py

#!/usr/bin/env python
#
# When triggered via a HTTP request, execute a command.
#
# Written by Senko Rasic <[email protected]>
# Released into Public Domain. Use it as you like.
#
# Usage: python trigger.py <host> <port> <key> <command>...
#
# HTTP GET and POST requests are supported. If you need more verbs or need
# to disable one of the two, edit the script. The request should have a
# "key" argument (via query string if GET, or body (urlencoded form) if POST),
# and the trigger is only activated if the key matches what's given on the
# command line.
#
# The command given on the commandline is executed (along with any arguments
# if given). If the command exits successfully (exit status 0), HTTP response
# code 200 is returned to the user, otherwise 500 is returned.
#
# Host is usually 0.0.0.0 (unless you want to listen only on a specific
# address/interface), port is the TCP port to listen on, key is the key
# that the client will have to supply to authorize the trigger, and the
# command is what should be executed.


from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
from subprocess import call, check_output, CalledProcessError, Popen, PIPE
import sys


class RequestHandler(BaseHTTPRequestHandler):
    key = None
    command = []

    def _parse_request(self):
        parsed_req = urlparse(self.path)
        args = parse_qs(parsed_req.query)
        if self.headers.get('content-type', '') \
            == 'application/x-www-form-urlencoded':
                body = self.rfile.read(int(self.headers.get('content-length')))
                args = parse_qs(body)

        ##args = dict((k, v[0]) for k, v in args.iteritems())
        return (parsed_req.path, args)

    def do_POST(self):
        path, args = self._parse_request()
        self.do('POST', path, args)

    def do_GET(self):
        path, args = self._parse_request()
        self.do('GET', path, args)

    def do(self, method, path, args):
        if args.get("key") is None:
            key = None
        else:
            key = args.get("key")[0]
        if args.get("servernumber") is None:
            servernumber = None
        else:
            servernumber = args.get("servernumber")[0]
        print(key)
        print(servernumber)
        if key != RequestHandler.key:
            self.send_error(400, 'Bad Request')
            return
        try:
            output = check_output(RequestHandler.command[0] + " " + str(servernumber))
        except CalledProcessError as e:
            output = b'Error!'
        if output != b'': 
            print("Process pre-lim status %s" % (output))
            retval = output.decode()
        else:
            retval = 0
        print("Process status: ", retval)
        if retval == 0:
            self.send_response(200, "Command success!")
            self.end_headers()
        elif retval == "Server already running\r\n":
            self.send_error(409, "Server already running")
        else:
            self.send_error(500, 'Trigger command failed')


def run(host, port, key, *command):
    RequestHandler.key = key
    print(RequestHandler.key)
    RequestHandler.command = command

    server = HTTPServer((host, port), RequestHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass

if __name__ == '__main__':
    if len(sys.argv) < 5:
        sys.stderr.write('Usage: %s <host> <port> <key> <cmd> ...\n' %
            sys.argv[0])
        sys.exit(-1)
    run(sys.argv[1], int(sys.argv[2]), sys.argv[3], *sys.argv[4:])
    sys.exit(0)

requesthandler.py

from subprocess import call, check_output, Popen, run
import sys, os
if __name__ == '__main__':
    def windowCheck(windowName):
    ##    return not check_output("tasklist /fi \"windowtitle eq {}\"".format(windowName)).decode() == 'INFO: No tasks are running which match the specified criteria.\r\n'
        return False
    req_args = str(sys.argv[1])
    # print("Our results: ", req_args)
    if req_args == "1" and not windowCheck("Stonkville Server"):
        os.system(["cmd.exe", "/c", "start", "cmd.exe", "/c", "c:/users/jonat/documents/stonkville server/run.bat"], shell=True)
    elif req_args == "1" and windowCheck("Stonkville Server"):
        print("Server already running")
    elif req_args == "2" and not windowCheck("Friend MC Server"):
        os.system(["cmd.exe", "/c", "start", "cmd.exe", "/c", "c:/users/jonat/documents/friend mc server/run.bat"], shell=True)
    elif req_args == "2" and windowCheck("Friend MC Server"):
        print("Server already running")
    elif req_args == "3" and not windowCheck("Hardcore Server"):
        run("cmd.exe /c start cmd.exe /c start cmd.exe /c start cmd.exe /k", shell=True)
    ##    Popen(["cmd.exe", "/c", "start", "cmd.exe", "/c", "c:/users/jonat/documents/hardcore server/run.bat"], shell=True)
    elif req_args == "3" and windowCheck("Hardcore Server"):
        print("Server already running")
    elif req_args == "-1":
        call(["cmd.exe", "/c", "start", "/wait", "cmd.exe", "/c", "StonkvilleShutdown.exe"])
    elif req_args == "-2":
        call(["cmd.exe", "/c", "start", "cmd.exe", "/c", "FriendShutdown.exe"])
    elif req_args == "-3":
        call(["cmd.exe", "/c", "start", "cmd.exe", "/c", "SurvivalShutdown.exe"])
    sys.exit(0)

Upvotes: 0

Views: 335

Answers (1)

Reda Bourial
Reda Bourial

Reputation: 866

There is a windows command that seems to do what you're looking for :


Start echo "hello world !"

man : https://ss64.com/nt/start.html

Upvotes: 0

Related Questions