0

这是我第一次发帖,我遇到了很多问题。与大多数希望他们的代码执行命令并等待它完成的人不同,我想在一个完全独立的新终端窗口中启动它。这是使用 Python HTTP 服务器,在终端窗口关闭之前,我无法在不暂停主线程的情况下运行它。我尝试了subprocess.call, subprocess.Popen, subprocess.run, os.system,但都没有奏效。我愿意接受任何建议。这是代码:

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 <senko.rasic@goodcode.io>
# 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)
4

1 回答 1

0

有一个 windows 命令似乎可以满足您的要求:


Start echo "hello world !"

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

于 2021-05-17T22:34:46.160 回答