Ejemplo n.º 1
0
    def print_output(self, strategy_results, output_format=None):

        if output_format is None:
            for vector_result in strategy_results:

                vector_name = vector_result.class_name
                header = vector_result.header
                banner = vector_result.banner
                output = vector_result.output
                if output:

                    print banner

                    if all(isinstance(i, list) for i in output) or all(isinstance(i, tuple) for i in output):
                        print tabulate(output, headers=header)
                    elif isinstance(output, str):
                        print "\n"
                        print output
                        print "\n"
                    else:
                        pprint(output)
                else:
                    print banner
                    print "No results Found."

        elif output_format is 'json':
            json_result = {}

            for vector_result in strategy_results:
                vector_name = vector_result.class_name
                header = vector_result.header
                output = vector_result.output
                if output and header:
                    cur_dict = {}

                    cur_json = general_utilities.list_and_headers_to_json(header, output)
                    cur_dict[vector_name] = cur_json
                    json_result.update(cur_dict)

            if json_result:
                json_result = json.dumps(json_result)
            else:
                json_result = {"result":[{"status":"No Results"}]}
                json_result = json.dumps(json_result)

            print json_result

        elif output_format is 'xml':
            # TODO
            pass
Ejemplo n.º 2
0
 def refresh(self):
     import os
     rows, columns = os.popen('stty size', 'r').read().split()
     tabulars = self.tabulars[-(int(rows) - 3):]
     sys.stdout.write("\x1b[2J\x1b[H")
     sys.stdout.write(tabulate(tabulars, self.headers))
     sys.stdout.write("\n")
Ejemplo n.º 3
0
    def rename(self):
        # Load actions
        init = (self.get('init').get(), None)[self.get('init').get() == ""]
        extension = ([
            x.strip() for x in self.get('extension').get().split(',')
        ], None)[self.get('extension').get() == ""]
        beginwith = self.get('beginwith').get()
        prefix = self.get('prefix').get()
        suffix = self.get('suffix').get()
        original = self.get('original').get()
        dirname = self.get('dirname').get()

        if (beginwith == ""): beginwith = ("001", "A")[init == "letter"]

        # Rule & Util
        rule = Rule(init, beginwith, prefix, dirname, suffix, extension,
                    original)

        if (self.simulation):
            action = Action(self.get('dirname').get(), rule)

            # Simulation
            header = ["Fichier original", "Renommé"]
            final = action.arrayEdit()

            # Debug (simulate with tabulate)
            print("")
            print(tabulate(final, header, tablefmt="simple"))

            return

        rename = Apply(self.get('dirname').get(), rule)
        rename.applyRename()
Ejemplo n.º 4
0
    def dump_tabular(self, *args, **kwargs):
        self.epoch += 1
        wh = kwargs.pop("write_header", None)

        self._try_to_sync_user_data()

        if len(self._tabular) > 0:
            if self._log_tabular_only:
                self.table_printer.print_tabular(self._tabular)
            else:
                for line in tabulate(self._tabular).split('\n'):
                    self.log(line, *args, **kwargs)
            tabular_dict = dict(self._tabular)

            # Only saves keys in first iteration to CSV!
            # (But every key is printed out in text)
            if self._tabular_keys is None:
                self._tabular_keys = list(sorted(tabular_dict.keys()))

            # Write to the csv files
            for tabular_fd in list(self._tabular_fds.values()):
                writer = csv.DictWriter(tabular_fd,
                                        fieldnames=self._tabular_keys,
                                        extrasaction="ignore",)
                if wh or (
                        wh is None and tabular_fd not in self._tabular_header_written):
                    writer.writeheader()
                    self._tabular_header_written.add(tabular_fd)
                writer.writerow(tabular_dict)
                tabular_fd.flush()
            if self.reopen_files_on_flush:
                new_tabular_fds = {}
                for k, fd in self._tabular_fds.items():
                    import shutil
                    from pathlib import Path
                    base_path = Path(fd.name)
                    copy_path = str(
                        base_path.parent / '{}{}'.format(
                            base_path.stem + '_copy',
                            base_path.suffix
                        )
                    )
                    shutil.copy(fd.name, copy_path)

                    new_fd = reopen(fd)
                    new_tabular_fds[k] = new_fd
                    if fd in self._tabular_header_written:
                        self._tabular_header_written.remove(fd)
                        self._tabular_header_written.add(new_fd)
                self._tabular_fds = new_tabular_fds
            del self._tabular[:]
Ejemplo n.º 5
0
 def dump_tabular(self, *args, **kwargs):
     wh = kwargs.pop("write_header", None)
     if len(self._tabular) > 0:
         if self._log_tabular_only:
             self.table_printer.print_tabular(self._tabular)
         else:
             for line in tabulate(self._tabular).split('\n'):
                 self.log(line, *args, **kwargs)
         tabular_dict = dict(self._tabular)
         # Also write to the csv files
         # This assumes that the keys in each iteration won't change!
         for tabular_fd in list(self._tabular_fds.values()):
             writer = csv.DictWriter(tabular_fd,
                                     fieldnames=list(tabular_dict.keys()))
             if wh or (
                     wh is None and tabular_fd not in self._tabular_header_written):
                 writer.writeheader()
                 self._tabular_header_written.add(tabular_fd)
             writer.writerow(tabular_dict)
             tabular_fd.flush()
         del self._tabular[:]
Ejemplo n.º 6
0
def main():
    args, parser = argparser()
    # if not args["target"] is None:
    #     target = ' '.join(args["target"])
    target = args["target"]
    strategy = args["strategy"]
    vector = args["vector"]
    # startegy_args = args["strategy_args"]
    vector_args = args["vector_args"]
    output_format = args["output"]
    show = args["show"]
    help_vector = args["help_vector"]
    help_strategy = args["help_strategy"]

    # const
    base_dir = os.path.dirname(os.path.realpath(__file__))
    vectors_file = base_dir + "/core/vectors.json"
    strategies_file = base_dir + "/core/strategies.json"
    # show!

    if show:
        if show == "vectors":
            vectors_conf, err = general_utilities.load_json(vectors_file)

            vectors_names = vectors_conf.keys()
            header = ["Vector", "Description", "Arguments"]
            data = []
            for vector_name in vectors_names:
                args = ', '.join(vectors_conf[vector_name]["args"])
                data.append([
                    vector_name, vectors_conf[vector_name]["description"], args
                ])

            print tabulate(data, headers=header, tablefmt="pipe")
            exit(0)
        elif show == "strategies":
            strategies_info = {}
            header = ["Strategy", "Vectors in Strategy"]
            strategies_info_list = []

            strategies_conf, err = general_utilities.load_json(strategies_file)
            for strategy_name in strategies_conf.keys():
                cur_item = []
                strategy_vectors = strategies_conf[strategy_name]["vectors"]
                strategies_vectors = ', '.join(strategy_vectors)
                cur_item.append(strategy_name)
                cur_item.append(strategies_vectors)
                strategies_info_list.append(cur_item)

            print tabulate(strategies_info_list, headers=header)
            exit(0)

    elif help_vector:

        vectors_conf, err = general_utilities.load_json(vectors_file)
        for vector_name in help_vector:
            if vector_name in vectors_conf.keys():
                print "%s:\n%s" % (vector_name,
                                   vectors_conf[vector_name]["description"])
            else:
                sys.stderr.write("%s: %s" % (vector_name, "not exist"))
                exit(1)
        exit(0)
    elif help_strategy:
        strategies_conf, err = general_utilities.load_json(strategies_file)

        for strategy_name in help_strategy:
            if strategy_name in strategies_conf.keys():
                print "%s:\n%s" % (
                    strategy_name,
                    strategies_conf[strategy_name]["description"])
            else:
                sys.stderr.write("%s: %s" % (strategy_name, "not exist"))
                exit(1)
        exit(0)
    else:

        if vector and strategy:
            sys.stderr.write("choose strategy or vector.")
            parser.print_help()
            exit(1)
        elif not vector and not strategy:
            sys.stderr.write("choose strategy or vector.")
            parser.print_help()
            exit(1)
        elif vector:
            vectors_conf, err = general_utilities.load_json(vectors_file)
            if err:
                sys.stderr.write(err)
                exit(1)
            else:
                if vector in vectors_conf.keys():
                    manager = ricco_manager(target,
                                            vector=vector,
                                            vector_args=vector_args,
                                            vectors_conf=vectors_conf,
                                            output_format=output_format)
                else:
                    sys.stderr.write("Vector not exist %s\n" % (vector, ))
                    exit(1)

        elif strategy:
            vectors_conf, err = general_utilities.load_json(vectors_file)

            strategies_conf, err = general_utilities.load_json(strategies_file)
            if err:
                sys.stderr.write(err)
                exit(1)
            else:
                if strategy in strategies_conf.keys():
                    manager = ricco_manager(target=target,
                                            strategy=strategy,
                                            strategies_conf=strategies_conf,
                                            vectors_conf=vectors_conf,
                                            output_format=output_format)
                else:
                    sys.stderr.write("Strategy not exist %s\n" % (strategy, ))
                    exit(1)

        vectors_instances = manager.prepare_vectors_list()
        manager.process(vectors_instances)
Ejemplo n.º 7
0
results = filter_results(results, query, CHECK_ALIVE)

if RECURSIVE:
    ips_to_check = []
    logging.debug("################## recursive #######################3")
    for item in results:
        cur_ips = item["ips"]
        ips_to_check = ips_to_check + cur_ips

    tmp_ips = check_ips(ips_to_check)
    results += (tmp_ips)

    results = filter_results(results, query)




#########################
# PRINTING
#########################
if HTML:
    json_for_web = {}
    json_for_web["data"] = results
    json_results = json.dumps(json_for_web)
    print json_results
elif JSON:
    json_results = json.dumps(results)
    print json_results
else:
    print tabulate(results, headers="keys")