Example #1
0
    def _diff(self, args):
        """
        Found the diff between revisions.

        Args:
            args(list): Command line arguments for diff
        """
        # I do like unified diff syntax
        if "-u" not in args:
            args.insert(0, "-u")

        opts = " ".join(args)
        spawn_str = "cvs diff {0}".format(opts)
        cvs_obj = self._access_cvs(spawn_str)
        if cvs_obj is not None:
            output = cvs_obj.before.decode("utf-8")
            output = output.split("\n")
            output = filter(lambda x: "cvs server:" not in x, output)
            output_colored = []
            for line in output:
                if line.startswith("+") and not line.startswith("+++"):
                    line = Fore.GREEN + line
                elif line.startswith("-") and not line.startswith("---"):
                    line = Fore.RED + line
                elif line.startswith("@@"):
                    line = Fore.CYAN + line
                output_colored.append(line)
            pydoc.pipepager("\n".join(output_colored), cmd="less -R")
Example #2
0
 def interactive_action(self, display_option=None):
     if display_option.display_text == self.ALL:
         doc = u''
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'),
                         cmd='less -R')
     else:
         if display_option.display_text == Constants.CASE_GET_ATTACH:
             lh = LaunchHelper(ListAttachments)
             lh.run('%s' % self.case)
         elif display_option.display_text == Constants.CASE_ADD_ATTACH:
             lh = LaunchHelper(AddAttachment)
             lh.run('-c %s' % self.case)
         elif display_option.display_text == Constants.CASE_ADD_COMMENT:
             lh = LaunchHelper(AddComment)
             lh.run('-c %s' % self.case)
             # Check if we need to reload the case as adding comments may
             # result in new options for case view.
             comments = self.case_obj.get_comments()
             if comments is None or len(comments) == 0:
                 self.postinit()
                 self.opts_updated = True
         elif (display_option.display_text == Constants.CASE_RECOMMENDATIONS
               and common.is_interactive()):
             lh = LaunchHelper(GenericPrompt)
             lh.run('', display_option)
         elif (display_option.display_text == Constants.CASE_MODIFY
               and common.is_interactive()):
             lh = LaunchHelper(ModifyCase)
             lh.run('%s' % self.case)
         else:
             doc = self._sections[display_option]
             pydoc.pipepager(doc.encode("UTF-8", 'replace'), cmd='less -R')
Example #3
0
def _page(output, pager_command=None):
    """Conditionally pipes the supplied output through a pager.

    :param output:
    :type output: object
    :param pager_command:
    :type pager_command: str
    """

    output = six.text_type(output)

    if not sys.stdout.isatty() or util.is_windows_platform():
        print(output)
        return

    num_lines = output.count('\n')
    exceeds_tty_height = pager.getheight() - 1 < num_lines

    if pager_command is None:
        pager_command = 'less -R'

    paginate = config.get_config_val("core.pagination") or True
    if exceeds_tty_height and paginate and \
            spawn.find_executable(pager_command.split(' ')[0]) is not None:
        pydoc.pipepager(output, cmd=pager_command)
    else:
        print(output)
Example #4
0
def _page(output, pager_command=None):
    """Conditionally pipes the supplied output through a pager.

    :param output:
    :type output: object
    :param pager_command:
    :type pager_command: str
    """

    output = six.text_type(output)

    if not sys.stdout.isatty() or util.is_windows_platform():
        print(output)
        sys.stdout.flush()
        return

    num_lines = output.count('\n')
    exceeds_tty_height = pager.getheight() - 1 < num_lines

    if pager_command is None:
        pager_command = 'less -R'

    try:
        paginate = config.get_config_val("core.pagination")
    except Exception:
        paginate = True
    if exceeds_tty_height and paginate and \
            spawn.find_executable(pager_command.split(' ')[0]) is not None:
        pydoc.pipepager(output, cmd=pager_command)
    else:
        print(output)
Example #5
0
File: util.py Project: moyiz/eg
def page_string(str_to_page, pager_cmd):
    """
    Page str_to_page via the pager. Tries to do a bit of fail-safe checking. For
    example, if the command starts with less but less doesn't appear to be
    installed on the system, it will resort to the pydoc.pager method.
    """
    # By default, we expect the command to be `less -R`. If that is the
    # pager_cmd, but they don't have less on their machine, odds are they're
    # just using the default value. In this case the pager will fail, so we'll
    # just go via pydoc.pager, which tries to do smarter checking that we don't
    # want to bother trying to replicate.
    # import ipdb; ipdb.set_trace()
    use_fallback_page_function = False
    if pager_cmd is None:
        use_fallback_page_function = True
    elif pager_cmd == FLAG_FALLBACK:
        use_fallback_page_function = True
    elif pager_cmd.startswith('less'):
        # stealing this check from pydoc.getpager()
        if hasattr(os, 'system') and os.system('(less) 2>/dev/null') != 0:
            # no less!
            use_fallback_page_function = True

    if use_fallback_page_function:
        pydoc.pager(str_to_page)
    else:
        # Otherwise, obey the user.
        pydoc.pipepager(str_to_page, cmd=pager_cmd)
Example #6
0
def paginate(text):
    """
    Send text to stdout with pagination

    If the function detects that the stdout is an interactive
    terminal then the supplied text will be piped via a
    paginator command.

    The pager command will be the default for ``pydoc``, but
    can be over-ridden by the ``PAGER`` environment variable.

    If stdout is not a terminal (for example if it's being
    set to a file, or piped to another command) then the
    pagination is skipped.

    Arguments:
      text (str): text to be printed using pagination

    """
    # If stdout is a terminal
    if os.isatty(sys.stdout.fileno()):
        # Acquire a pager command
        try:
            pager = os.environ["PAGER"]
        except KeyError:
            pager = None
        # Output the prediction with paging
        if pager is not None:
            pydoc.pipepager(text,cmd=pager)
        else:
            pydoc.pager(text)
    else:
        # Stdout not a terminal
        print(text)
Example #7
0
def analyze(db, proof=False):
    headerbytes = db.read(100)
    offset = 100
    header = Header(headerbytes)
    print(header.info(proof))
    p = db.read(header.get_page_size()[0] - 100)
    b = BTreePage(p, 1, 100, offset)
    offset = header.get_page_size()[0]
    pages = [b]
    overview = b.shortinfo() + "\n"
    for i in range(2, header.get_db_size()[0]+1):
        p = db.read(header.get_page_size()[0])
        b = BTreePage(p, i, offset)
        if(b.get_pagetype()[1] == 0x00):
            f = FreeTrunkPage(b.pagebytes)
            overview += "Potential free-page, Offset: 0x%08x, Number: %d, Next Trunk: %d, #Leafes:%d\n" % (
                offset, i, f.get_next_trunk_page()[0], f.get_pointer_count()[0])
        else:
            overview += b.shortinfo() + "\n"
        offset += header.get_page_size()[0]
        pages.append(b)
    if(header.get_db_size()[0] > 30):
        pydoc.pipepager(colorblue+"Showing overview of pages:\n"+coloroff+overview, cmd='less -R')
    else:
        print(overview)
    interactive(header, pages, overview)
Example #8
0
def _page(output, pager_command=None):
    """Conditionally pipes the supplied output through a pager.

    :param output:
    :type output: object
    :param pager_command:
    :type pager_command: str
    """

    output = str(output)

    if pager_command is None:
        pager_command = 'less -R'

    if not sys.stdout.isatty() or util.is_windows_platform():
        print(output)
        return

    num_lines = output.count('\n')
    exceeds_tty_height = pager.getheight() - 1 < num_lines

    if exceeds_tty_height:
        pydoc.pipepager(output, cmd=pager_command)
    else:
        print(output)
Example #9
0
def exploit(profile, workspace):
    now = datetime.now()
    dt_string = now.strftime("%d_%m_%Y_%H_%M_%S")
    file = "{}_iam_list_groups".format(dt_string)
    filename = "./workspaces/{}/{}".format(workspace, file)
    try:
        iam_details = profile.list_groups()
        while iam_details['IsTruncated']:
            iam_details = profile.list_groups(Marker=iam_details['Marker'])

        groups = iam_details['Groups']
        with open(filename, 'w') as outputfile:
            json.dump(groups, outputfile, indent=4, default=str)

        outputfile.close()
        print(colored("[*] Output written to file", "green"), colored("'{}'".format(filename), "blue"),
              colored(".", "green"))

        output = ""
        for iam in iam_details['Groups']:
            output +=("{}\n".format(colored("-----------------------------", "yellow", attrs=['bold'])))
            output +=("{}:\t{}\n".format(colored("IAM", "yellow", attrs=['bold']), iam['GroupName']))
            output +=("{}\n".format(colored("-----------------------------", "yellow", attrs=['bold'])))
            for key,value in iam.items():
                output +=("\t{}:\t{}\n".format(colored(key,"red",attrs=['bold']), colored(value,"blue")))
            output += "\n"
        pipepager(output, cmd='less -R')

    except:
        e = sys.exc_info()[0]
        print(colored("[*] {}".format(e), "red"))
Example #10
0
    def print(self):
        rows, columns = os.popen("stty size", "r").read().split()
        print(
            f"{fontColor(style = Style.ITALIC)}{self._note.min_path}{fontReset()}"
        )

        raw_markdown = self._read_raw_markdown()

        mdv.term_columns = 60
        if config.get("view-mode") == "interactive":
            pydoc.pipepager(
                mdv.main(
                    raw_markdown,
                    theme=self._MDV_theme_id,
                    header_nrs=self._MDV_headers,
                ),
                cmd="less -R",
            )
        elif config.get(
                "view-mode") == "combo" and len(raw_markdown) > int(rows):
            pydoc.pipepager(
                mdv.main(
                    raw_markdown,
                    theme=self._MDV_theme_id,
                    header_nrs=self._MDV_headers,
                ),
                cmd="less -R",
            )
        else:
            print(mdv.main(raw_markdown))
Example #11
0
 def interactive_action(self, display_option=None):
     if display_option.display_text == self.ALL:
         doc = u''
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'), cmd='less -R')
     else:
         if display_option.display_text == Constants.CASE_GET_ATTACH:
             lh = LaunchHelper(ListAttachments)
             lh.run('%s' % self.case)
         elif display_option.display_text == Constants.CASE_ADD_ATTACH:
             lh = LaunchHelper(AddAttachment)
             lh.run('-c %s' % self.case)
         elif display_option.display_text == Constants.CASE_ADD_COMMENT:
             lh = LaunchHelper(AddComment)
             lh.run('-c %s' % self.case)
             # Check if we need to reload the case as adding comments may
             # result in new options for case view.
             comments = self.case_obj.get_comments()
             if comments is None or len(comments) == 0:
                 self.postinit()
                 self.opts_updated = True
         elif (display_option.display_text == Constants.CASE_RECOMMENDATIONS
               and common.is_interactive()):
             lh = LaunchHelper(GenericPrompt)
             lh.run('', display_option)
         elif (display_option.display_text == Constants.CASE_MODIFY
               and common.is_interactive()):
             lh = LaunchHelper(ModifyCase)
             lh.run('%s' % self.case)
         else:
             doc = self._sections[display_option]
             pydoc.pipepager(doc.encode("UTF-8", 'replace'), cmd='less -R')
Example #12
0
def show_info(func, func_name):
    """
    Shows all available information about a 
    """
    logging.info('Does not show constants')
    result = ''
    for i, f in enumerate(func):
        try:
            if f['name'] == func_name:
                a = f['arguments']['argument']
                result += 'Name: %s\n' % f['name']
                result += '\nDll: %s\n' % f['dll']
                result += str_format('\nDescription: %s\n' % f['description'])
                result += '\n'
                result += str_format('\nReturns: %s\n' % f['returns'])
                result += '\n'
                if isinstance(a, list):
                    ag = [
                        '\n%s: %s\n' % (x['name'], x['description']) for x in a
                    ]
                    arguments = '\n'.join(ag)
                elif isinstance(a, dict):
                    arguments = '%s: %s' % (a['name'], a['description'])
                result += str_format('\nArguments: \n%s' % arguments)
                result += '\n\nMSFT URL: https://social.msdn.microsoft.com/search/en-US/windows?query=%s' % f[
                    'name']
        except TypeError:
            continue
    pipepager(result, cmd='less -R')
Example #13
0
def _page(output, pager_command=None):
    """Conditionally pipes the supplied output through a pager.

    :param output:
    :type output: object
    :param pager_command:
    :type pager_command: str
    """

    output = six.text_type(output)

    if pager_command is None:
        pager_command = 'less -R'

    if not sys.stdout.isatty() or util.is_windows_platform():
        print(output)
        return

    num_lines = output.count('\n')
    exceeds_tty_height = pager.getheight() - 1 < num_lines

    paginate = util.get_config().get("core.pagination", True)
    if exceeds_tty_height and paginate:
        pydoc.pipepager(output, cmd=pager_command)
    else:
        print(output)
Example #14
0
    def _diff(self, args):
        """
        Found the diff between revisions.

        Args:
            args(list): Command line arguments for diff
        """
        # I do like unified diff syntax
        if "-u" not in args:
            args.insert(0, "-u")

        opts = " ".join(args)
        spawn_str = "cvs diff {0}".format(opts)
        cvs_obj = self._access_cvs(spawn_str)
        if cvs_obj is not None:
            output = cvs_obj.before.decode("utf-8")
            output = output.split("\n")
            output = filter(lambda x: "cvs server:" not in x, output)
            output_colored = []
            for line in output:
                if line.startswith("+") and not line.startswith("+++"):
                    line = Fore.GREEN + line
                elif line.startswith("-") and not line.startswith("---"):
                    line = Fore.RED + line
                elif line.startswith("@@"):
                    line = Fore.CYAN + line
                output_colored.append(line)
            pydoc.pipepager("\n".join(output_colored), cmd="less -R")
Example #15
0
def main():
    """
    Reads in a specified file, removes trailing whitespace, and re-saves.
    """
    # Open file and store lines as str list
    try:
        file_handler = open(ARGS.filename, 'r+')
    except IOError:
        print(traceback.format_exc())  # pylint: disable=C0325
        sys.exit()

    lines_of_text = file_handler.readlines()
    file_handler.seek(0)

    # Preview and write text back to file and close file
    print(lines_of_text)  # pylint: disable=C0325
    Cli.wait()
    string = ''
    preview_string = ''
    for index, _ in enumerate(lines_of_text):
        string += lines_of_text[index].rstrip() + '\n'
        preview_string = string.strip() + Cli.term_fx('b', 'EOL')
    pydoc.pipepager(preview_string, cmd='less -R')
    try:
        char = Cli.get_keypress('Write to file?')
        assert char == 'y'
        file_handler.write(string)
    except AssertionError:
        print('File not saved.  Good bye.')  # pylint: disable=C0325
    finally:
        file_handler.close()
Example #16
0
File: eg_util.py Project: Ferdov/eg
def page_string(str_to_page, pager_cmd):
    """
    Page str_to_page via the pager. Tries to do a bit of fail-safe checking. For
    example, if the command starts with less but less doesn't appear to be
    installed on the system, it will resort to the pydoc.pager method.
    """
    # By default, we expect the command to be `less -R`. If that is the
    # pager_cmd, but they don't have less on their machine, odds are they're
    # just using the default value. In this case the pager will fail, so we'll
    # just go via pydoc.pager, which tries to do smarter checking that we don't
    # want to bother trying to replicate.
    # import ipdb; ipdb.set_trace()
    use_fallback_page_function = False
    if pager_cmd is None:
        use_fallback_page_function = True
    elif pager_cmd == FLAG_FALLBACK:
        use_fallback_page_function = True
    elif pager_cmd.startswith('less'):
        # stealing this check from pydoc.getpager()
        if hasattr(os, 'system') and os.system('(less) 2>/dev/null') != 0:
            # no less!
            use_fallback_page_function = True

    if use_fallback_page_function:
        pydoc.pager(str_to_page)
    else:
        # Otherwise, obey the user.
        pydoc.pipepager(str_to_page, cmd=pager_cmd)
Example #17
0
def exploit(profile, workspace):
    tag_status = variables['TAG-STATUS']['value']
    if tag_status == 'TAGGED' or tag_status == 'UNTAGGED' or tag_status == 'ANY':
        n_tab = 0
        global output

        now = datetime.now()
        dt_string = now.strftime("%d_%m_%Y_%H_%M_%S")
        file = "{}_ecr_list_images".format(dt_string)
        filename = "./workspaces/{}/{}".format(workspace, file)

        repo_name = variables['REPO-NAME']['value']
        reg_id = variables['REGISTRY-ID']['value']

        kwargs = {
            "repositoryName": repo_name,
            "filter": {
                'tagStatus': tag_status
            },
            "maxResults": 1000
        }

        if not reg_id == '':
            kwargs['registryId'] = reg_id

        response = profile.list_images(**kwargs)
        json_data = response['imageIds']

        while 'nextToken' in response:
            kwargs['nextToken'] = response['nextToken']
            response = profile.list_images(**kwargs)
            json_data.extend(response['imageIds'])

        with open(filename, 'w') as outfile:
            json.dump(json_data, outfile, indent=4, default=str)
            print(
                colored("[*] Content dumped on file '{}'.".format(filename),
                        "green"))

        if isinstance(json_data, list):
            output += colored("---------------------------------\n",
                              "yellow",
                              attrs=['bold'])
            for data in json_data:
                list_dictionary(data, n_tab)
                output += colored("---------------------------------\n",
                                  "yellow",
                                  attrs=['bold'])
        else:
            output += colored("---------------------------------\n",
                              "yellow",
                              attrs=['bold'])
            list_dictionary(json_data, n_tab)
            output += colored("---------------------------------\n",
                              "yellow",
                              attrs=['bold'])
        pipepager(output, "less -R")
        output = ""
Example #18
0
def less(text):
    """View text via 'less' terminal pager.

    :param text: The text to view.
    """
    if isinstance(text, StringIO):
        text = text.getvalue()

    pipepager(text, cmd="less -FRSX")
Example #19
0
def usage1d(code):
    try:
        help_fp = file("1d_orig_help.txt", "r")
        help_txt = help_fp.read()
    except:
        print "Can't find the help file - should be called '1d_orig_help.txt' - Did you rename it?"
        sys.exit(code)
    pipepager(help_txt, '/usr/bin/less -NS')  # pipe help text into 'less -NS'
    sys.exit(code)
Example #20
0
def show_project_details(data, width):
    doc = doc_generator.generate_doc(data, width)
    doc = doc.format(
        head='\033[0;33m',
        project='\033[1;36m',
        command='\033[1;33m',
        reset='\033[0m'
    )
    pydoc.pipepager(doc, cmd='less -R')
Example #21
0
 def doinst_sh(self):
     """doinst.sh handler file
     """
     os.system("clear")
     temp = "\n".join(doinst.splitlines())
     pydoc.pipepager(temp, cmd='less -R')
     self.filename = "doinst.sh"
     self.edit()
     self.menu()
Example #22
0
 def doinst_sh(self):
     """doinst.sh handler file
     """
     os.system("clear")
     temp = "\n".join(doinst.splitlines())
     pydoc.pipepager(temp, cmd='less -R')
     self.filename = "doinst.sh"
     self.edit()
     self.menu()
Example #23
0
def cmd_show(*args):
    """
    :show <host>          Show the output of the last command for <host>.
    :<host>               A shortcut for `:show <host>`
    """
    if len(args) == 1:
        host = args[0]
        host = connections.conns._gethost(host)
        if not host:
            terminal.error(text = "No such host")
            return os.EX_OK
        history = connections.conns.get_history(host)
        if not history:
            terminal.error(text = "No output available for %s" % host)
        else:
            last_history = history[-1]
            command = last_history.get('command')
            output = last_history.get('output')
            exitcode = last_history.get('exitcode')

            if exitcode is None:
                terminal.error(text = "Command still pending")
                return os.EX_OK
            else:
                # This will block if the process isn't complete
                outlines = output.readlines()
                # Reset the output for later re-reading. If we've already
                # replaced the buffer with a StringIO we can just seek.
                try:
                    output.seek(0)
                except:
                    output = StringIO.StringIO()
                    output.writelines(outlines)
                    output.seek(0)
                last_history['output'] = output
            outstr = ''
            outstr += terminal.error(
                text = terminal.tocolor(command + '\n', 'bold'),
                silent = True
            )
            for line in outlines:
                outstr += terminal.error(
                    '[%s] ' % host,
                    line.strip('\n'),
                    1,
                    silent = True
                )
            outstr += terminal.error(
                text = 'Exit code: %s' % exitcode,
                silent = True
            )
            outstr = outstr.replace('\r', '\n')
            pydoc.pipepager(outstr, config.get('pager'))
    else:
        return os.EX_USAGE
    return os.EX_OK
Example #24
0
 def interactive_action(self, display_option=None):
     if display_option.display_text == self.ALL:
         doc = u""
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", "replace"), cmd="less -R")
     else:
         doc = self._sections[display_option]
         pydoc.pipepager(doc.encode("UTF-8", "replace"), cmd="less -R")
Example #25
0
 def interactive_action(self, display_option=None):
     if display_option.display_text == self.ALL:
         doc = u''
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'), cmd='less -R')
     else:
         doc = self._sections[display_option]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'), cmd='less -R')
Example #26
0
def main():
    args = get_args()
    username, password = get_creds()
    url = args.log_url
    r = requests.get(url, auth=(username, password))

    if args.raw:
        pydoc.pipepager(r.text, cmd='less')
    elif args.errors:
        filter_errors(r.text)
    def test_pipepager(self):
        # pipepager does not choke on unicode
        doc = pydoc.render_doc(self.Q)

        saved, os.popen = os.popen, open
        try:
            with test.test_support.temp_cwd():
                pydoc.pipepager(doc, 'pipe')
                self.assertEqual(open('pipe').read(), pydoc._encode(doc))
        finally:
            os.popen = saved
    def test_pipepager(self):
        # pipepager does not choke on unicode
        doc = pydoc.render_doc(self.Q)

        saved, os.popen = os.popen, open
        try:
            with test.test_support.temp_cwd():
                pydoc.pipepager(doc, 'pipe')
                self.assertEqual(open('pipe').read(), pydoc._encode(doc))
        finally:
            os.popen = saved
Example #29
0
def _pageDoc(title, docString):
    docString = _formatDocString(docString)
    # pydoc is fooled by conary's wrapping of stdout. override it if needed.
    if sys.stdout.isatty():
        if _useLess():
            # -R parses CSR escape codes properly
            pydoc.pager = lambda x: pydoc.pipepager(x, 'less -R')
        else:
            # PAGER is set if _useLess returns False
            pydoc.pager = lambda x: pydoc.pipepager(x, os.environ['PAGER'])
    pydoc.pager("Conary API Documentation: %s\n" %
                _formatString('B{' + title + '}') + docString)
Example #30
0
def _pageDoc(title, docString):
    docString = _formatDocString(docString)
    # pydoc is fooled by conary's wrapping of stdout. override it if needed.
    if sys.stdout.isatty():
        if _useLess():
            # -R parses CSR escape codes properly
            pydoc.pager = lambda x: pydoc.pipepager(x, 'less -R')
        else:
            # PAGER is set if _useLess returns False
            pydoc.pager = lambda x: pydoc.pipepager(x, os.environ['PAGER'])
    pydoc.pager("Conary API Documentation: %s\n" %
            _formatString('B{' + title + '}') + docString)
def exploit(profile, workspace):
	n_tab = 0
	global output

	now = datetime.now()
	dt_string = now.strftime("%d_%m_%Y_%H_%M_%S")
	file = "{}_route53_list_hosted_zones".format(dt_string)
	filename = "./workspaces/{}/{}".format(workspace, file)
	hosted_zones = []

	response = profile.list_hosted_zones()
	while response['IsTruncated']:
		response.extend(profile.list_hosted_zones(Marker=response['Marker']))

	for hostedzone in response['HostedZones']:
		try:
			if not hostedzone["ResourceRecordSetCount"] == 0:
				response2 = profile.list_resource_record_sets(
					HostedZoneId=hostedzone['Id']
				)
				while response2['IsTruncated']:
					response2 = profile.list_resource_record_sets(
						HostedZoneId = hostedzone['Id'],
						Marker = response2['Marker']
					)

				hostedzone['ResourceRecordSets'] = response2['ResourceRecordSets']

		except:
			e = sys.exc_info()[1]
			print(colored("[*] {}".format(e), "red"))

	json_data = response['HostedZones']
	with open(filename, 'w') as outfile:
		json.dump(json_data, outfile, indent=4, default=str)
		print(colored("[*] Content dumped on file '{}'.".format(filename), "green"))

	title_name = "Name"
	if isinstance(json_data, list):
		output += colored("---------------------------------\n", "yellow", attrs=['bold'])
		for data in json_data:
			output += colored("{}: {}\n".format(title_name, data[title_name]), "yellow", attrs=['bold'])
			output += colored("---------------------------------\n", "yellow", attrs=['bold'])
			list_dictionary(data, n_tab)
			output += colored("---------------------------------\n", "yellow", attrs=['bold'])
	else:
		output += colored("---------------------------------\n", "yellow", attrs=['bold'])
		output += colored("{}: {}\n".format(title_name, json_data[title_name]), "yellow", attrs=['bold'])
		output += colored("---------------------------------\n", "yellow", attrs=['bold'])
		list_dictionary(json_data, n_tab)
		output += colored("---------------------------------\n", "yellow", attrs=['bold'])
	pipepager(output, "less -R")
	output = ""
Example #32
0
    def print_code_to_console(self, output_code):
        if not output_code.startswith('{{task'):
            if not self.args['colorscheme']:
                pager(output_code)
            else:
                pipepager(self._get_colored_output(output_code), cmd='less -R')

        # No modifications done to the raw algorithm means no match was found
        # for that specific language/algorithm
        else:
            _print_error(
                f'No results found for {self.formal_algorithm} using {self.formal_language}')
Example #33
0
 def interactive_action(self, display_option=None):
     if display_option.display_text == self.ALL:
         doc = u''
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'),
                         cmd='less -R')
     else:
         sol_id = display_option.stored_obj
         lh = LaunchHelper(Kb)
         lh.run(sol_id)
def exploit(profile, workspace):
    n_tab = 0
    global output

    dt_string = (datetime.now()).strftime("%d_%m_%Y_%H_%M_%S")
    file = "{}_ec2_enum_public_ipv4_ip_pools".format(dt_string)
    filename = "./workspaces/{}/{}".format(workspace, file)
    output = ""
    response = profile.describe_public_ipv4_pools()['PublicIpv4Pools']

    if len(response) == 0:
        print(colored('[*] No Public IPv4 Pools configured!', 'red'))
    else:
        with open(filename, 'w') as user_filename:
            json.dump(response, user_filename, indent=4, default=str)
        print(
            colored(
                "[*] IP Pools output is dumped on file '{}'.".format(filename),
                "yellow"))

        if isinstance(response, list):
            output += colored("---------------------------------\n",
                              "yellow",
                              attrs=['bold'])
            for data in response:
                output += colored("PublicIp: {}\n".format(response['PoolId']),
                                  "yellow",
                                  attrs=['bold'])
                output += colored("---------------------------------\n",
                                  "yellow",
                                  attrs=['bold'])
                list_dictionary(data, n_tab)
                output += colored("---------------------------------\n",
                                  "yellow",
                                  attrs=['bold'])
        else:
            output += colored("---------------------------------\n",
                              "yellow",
                              attrs=['bold'])
            output += colored("PublicIp: {}\n".format(response['PoolId']),
                              "yellow",
                              attrs=['bold'])
            output += colored("---------------------------------\n",
                              "yellow",
                              attrs=['bold'])
            list_dictionary(response, n_tab)
            output += colored("---------------------------------\n",
                              "yellow",
                              attrs=['bold'])

        pipepager(output, cmd='less -R')
        output = ""
Example #35
0
    def _log(self, args):
        """
        Display the log of commits of files.

        Args:
            args(list): Command line arguments for log
        """
        opts = " ".join(args)
        spawn_str = "cvs log {0}".format(opts)
        cvs_obj = self._access_cvs(spawn_str)
        if cvs_obj is not None:
            output = cvs_obj.before.decode("utf-8")
            pydoc.pipepager(output, cmd="less -R")
Example #36
0
def print_subject(file_name, opt):
    to_print = UNDERLINED_BLUE + file_name + ':' + VANILLA + '\n'

    with open(file_path.format(file=file_name), 'r') as f:
        for line in f:
            if line.startswith('#'):
                to_print += BLUE + line + VANILLA
            else:
                to_print += line
        if opt == less:
            pydoc.pipepager(to_print, 'less -R')
        else:
            print(to_print)
Example #37
0
    def _log(self, args):
        """
        Display the log of commits of files.

        Args:
            args(list): Command line arguments for log
        """
        opts = " ".join(args)
        spawn_str = "cvs log {0}".format(opts)
        cvs_obj = self._access_cvs(spawn_str)
        if cvs_obj is not None:
            output = cvs_obj.before.decode("utf-8")
            pydoc.pipepager(output, cmd="less -R")
Example #38
0
def exploit(profile, workspace):
    buckets = variables['BUCKETS']['value'].split(",")
    contents = {}
    now = datetime.now()
    dt_string = now.strftime("%d_%m_%Y_%H_%M_%S")
    file = "{}_iam_enum_all".format(dt_string)
    filename = "./workspaces/{}/{}".format(workspace, file)

    json_data = {}
    for buck in buckets:
        maxkeys = int(variables['MAXKEYS']['value'])
        response = profile.list_objects_v2(Bucket=buck, MaxKeys=maxkeys)

        contents[buck] = response['Contents']
        while response['IsTruncated']:
            response = profile.list_objects_v2(
                Bucket=buck,
                MaxKeys=maxkeys,
                ContinuationToken=response['NextContinuationToken'])
            contents[buck].extend(response['Contents'])
        json_data[buck] = response['Contents']

    with open(filename, 'w') as outputfile:
        json.dump(json_data, outputfile, indent=4, default=str)

    outputfile.close()
    print(colored("[*] Output written to file", "green"),
          colored("'{}'".format(filename), "blue"), colored(".", "green"))

    output = ""
    for key, value in json_data.items():
        output += (colored("-----------------------------\n",
                           "yellow",
                           attrs=["bold"]))
        output += ("{}: {}".format(colored("Name:", "yellow", attrs=["bold"]),
                                   colored("\t{}\n".format(key), "white")))
        output += (colored("-----------------------------\n",
                           "yellow",
                           attrs=["bold"]))

        output += (colored("\t\t-----------------------------\n",
                           "yellow",
                           attrs=["bold"]))
        for x in value:
            for k, v in x.items():
                output += ("\t\t{}:\t{}\n".format(colored(k, "red"),
                                                  colored(v, "blue")))
            output += (colored("\t\t-----------------------------\n",
                               "yellow",
                               attrs=["bold"]))
    pipepager(output, "less -R")
def exploit(profile, workspace):
    now = datetime.now()
    dt_string = now.strftime("%d_%m_%Y_%H_%M_%S")
    file = "{}_ec2_enum_security_groups".format(dt_string)
    filename = "./workspaces/{}/{}".format(workspace, file)

    if (variables['GROUPID']['value']) == "":
        try:
            response = profile.describe_security_groups()
            #while response.get('NextToken'):
            #	response = profile.describe_snapshots(
            #		NextToken=response['NextToken']
            #	)
            with open(filename, 'w') as snap_file:
                json.dump(response['SecurityGroups'],
                          snap_file,
                          indent=4,
                          default=str)

            output = print_output(response)
            pipepager(output, cmd='more')
            print(
                colored("[*] Content dumped on file '{}'.".format(filename),
                        "green"))

        except botocore.exceptions.ClientError:
            print(
                colored("[*] Check internet connection.".format(filename),
                        "red"))

    else:
        try:
            secgroups = (variables['GROUPID']['value']).split(",")
            response = profile.describe_security_groups(GroupIds=secgroups)
            with open(filename, 'w') as snap_file:
                json.dump(response['SecurityGroups'],
                          snap_file,
                          indent=4,
                          default=str)

            output = print_output(response)
            pipepager(output, cmd='more')
            print(
                colored("[*] Content dumped on file '{}'.".format(filename),
                        "green"))

        except botocore.exceptions.ClientError:
            print(
                colored(
                    "[*] Check all the Snapshot IDs provided. Some might be incorrect. Else, check internet connection."
                    .format(filename), "red"))
Example #40
0
def cmd_show(*args):
    """
    :show <host>          Show the output of the last command for <host>.
    :<host>               A shortcut for `:show <host>`
    """
    if len(args) == 1:
        host = args[0]
        host = connections.conns._gethost(host)
        if not host:
            terminal.error(text="No such host")
            return os.EX_OK
        history = connections.conns.get_history(host)
        if not history:
            terminal.error(text="No output available for %s" % host)
        else:
            last_history = history[-1]
            command = last_history.get('command')
            output = last_history.get('output')
            exitcode = last_history.get('exitcode')

            if exitcode is None:
                terminal.error(text="Command still pending")
                return os.EX_OK
            else:
                # This will block if the process isn't complete
                outlines = output.readlines()
                # Reset the output for later re-reading. If we've already
                # replaced the buffer with a StringIO we can just seek.
                try:
                    output.seek(0)
                except:
                    output = StringIO.StringIO()
                    output.writelines(outlines)
                    output.seek(0)
                last_history['output'] = output
            outstr = ''
            outstr += terminal.error(text=terminal.tocolor(
                command + '\n', 'bold'),
                                     silent=True)
            for line in outlines:
                outstr += terminal.error('[%s] ' % host,
                                         line.strip('\n'),
                                         1,
                                         silent=True)
            outstr += terminal.error(text='Exit code: %s' % exitcode,
                                     silent=True)
            outstr = outstr.replace('\r', '\n')
            pydoc.pipepager(outstr, config.get('pager'))
    else:
        return os.EX_USAGE
    return os.EX_OK
Example #41
0
def print_obj(obj, desc, output='@EDITOR', tmpPrefix='', suffix='.json'):
    """Send *obj* to pager/terminal/subprocess/file."""
    tmpPrefix += '-'
    if suffix == '.json' and not isinstance(obj, str):
        obj = prettify_json(obj)
    if output == '@pager':
        print(c.yellow("Printing {} to pager . . .\n".format(desc)))
        pipepager(obj, cmd='less -R')
    elif output == '@term':
        print(c.yellow("Printing {} to terminal . . .\n".format(desc)))
        print(obj)
    elif output == '@EDITOR':
        if environ.has_key('RAVSH_EDITOR') and find_executable(
                environ['RAVSH_EDITOR']):
            cmd = environ['RAVSH_EDITOR']
        elif environ.has_key('EDITOR') and find_executable(environ['EDITOR']):
            cmd = environ['EDITOR']
        elif environ.has_key('DISPLAY') and find_executable('gvim'):
            cmd = 'gvim'
        elif find_executable('vim'):
            cmd = 'vim'
        else:
            print(c.yellow("Printing {} to pager . . .\n".format(desc)))
            pipepager(obj, cmd='less -R')
            return
        print(
            c.yellow(
                "Saving {} to tmpfile & opening w/cmd '{}' . . .\n".format(
                    desc, cmd)))
        tmp = NamedTemporaryFile(prefix=tmpPrefix, suffix=suffix, delete=False)
        tmp.write(obj)
        tmp.flush()
        subprocess.call([cmd, tmp.name])
    else:
        output = path.expanduser(output)
        if suffix:
            output += suffix
        try:
            prepare_file_for_writing(output)
        except:
            return
        try:
            with open(output, 'w') as f:
                f.write(obj)
        except IOError as e:
            print(
                c.RED("Problem exporting {} to file: '{}'\n"
                      "  {}\n".format(desc, output, e)))
            return
        print(c.green("Exported {} to file: '{}'\n".format(desc, output)))
Example #42
0
 def interactive_action(self, display_option=None):
     if display_option.display_text == self.ALL:
         doc = u''
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'),
                         cmd='less -R')
     # Used by GetCase
     else:
         uuid = None
         uuid = display_option.stored_obj
         lh = LaunchHelper(GetAttachment)
         lh.run('-c %s -u %s' % (self.case, uuid))
Example #43
0
 def interactive_action(self, display_option=None):
     '''
     This gets invoked when running in interactive mode
     Basically just a hook to get your sub command (symptom) invoked
     '''
     if display_option.display_text == self.ALL:
         doc = u''
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'), cmd='less -R')
     else:
         lh = LaunchHelper(Symptom)
         lh.run(None, display_option)
def exploit(profile, workspace):
	try:
		now = datetime.now()
		dt_string = now.strftime("%d_%m_%Y_%H_%M_%S")
		file = "{}_lambda_list_alias".format(dt_string)
		filename = "./workspaces/{}/{}".format(workspace, file)
		workspaces = {}
		functionname = variables['FUNCTIONNAME']['value']
		functionversion = variables['FUNCTIONVERSION']['value']

		if not functionversion == "":
			response = profile.list_aliases(
				FunctionName=functionname,
				FunctionVersion=functionversion,
				MaxItems=10000
			)['Aliases']
		else:
			response = profile.list_aliases(
				FunctionName=functionname,
				MaxItems=10000
			)['Aliases']

		if not response:
			print(colored("[*] There are no aliases for this function.", "green"))
		else:
			with open(filename, 'w') as outfile:
				json.dump(response, outfile, indent=4, default=str)
				print(colored("[*] Content dumped on file '{}'.".format(filename), "green"))

			output = ""
			for alias in response:
				output += (colored("------------------------------------------------\n", "yellow", attrs=['bold']))
				output += ("{}: {}\n".format(colored("Name", "yellow", attrs=['bold']), alias['Name']))
				output += (colored("------------------------------------------------\n", "yellow", attrs=['bold']))
				for key,value in alias.items():
					if key == 'RoutingConfig':
						output += ("\t{}: \n".format(colored("RoutingConfig", "red", attrs=['bold'])))
						for k,v in value.items():
							output += ("\t\t{}: {}\n".format(colored(k, "blue", attrs=['bold']), colored(v, "yellow")))
					else:
						output += ("\t{}: {}\n".format(colored(key, "red", attrs=['bold']), colored(value, "blue")))
			output += "\n"
			pipepager(output, cmd='less -R')
	
	except profile.exceptions.ResourceNotFoundException:
		print(colored("[*] The function does not exist. Check the name.", "red"))
	
	except:
		e = sys.exc_info()
		print(colored("[*] {}".format(e), "red"))
Example #45
0
 def interactive_action(self, display_option=None):
     '''
     This gets invoked when running in interactive mode
     Basically just a hook to get your sub command (symptom) invoked
     '''
     if display_option.display_text == self.ALL:
         doc = u''
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'),
                         cmd='less -R')
     else:
         lh = LaunchHelper(Symptom)
         lh.run(None, display_option)
Example #46
0
def parse_dir(d):
    d = os.path.expanduser(d)
    d = os.path.join(d, "profile", "profile")
    exe = 'opreport'
    if args.annotate:
        exe = 'opannotate'
    cmd = "%s -p %s " % (exe, args.path)
    cmd += " -m all "
    cmd += " --session-dir %s " % d
    cmd += " session:profile "
    if args.event == "cycles":
        cmd += " event:CPU_CLK_UNHALTED "
    elif args.event == "l1miss":
        cmd += " event:L1D "
    elif args.event == "llcmiss":
        cmd += " event:LLC_MISS "
    if not args.annotate:
        cmd += " -a -l "
    else:
        cmd += " -s "
        cmd += ' -d ~/iso '
    cmd += ' %s ' % args.args
    if args.exclusive:
        if not args.annotate:
            cmd += " | egrep -i 'perfiso.ko'"
        else:
            cmd += " --include-file %s " % PERFISO_FILES

    if args.cmd:
        print cmd
    else:
        return pydoc.pipepager(filter_output(cmd), "less -R")
Example #47
0
 def interactive_action(self, display_option=None):
     if display_option.display_text == self.ALL:
         doc = u''
         for opt in self._submenu_opts:
             if opt.display_text != self.ALL:
                 doc += self._sections[opt]
         pydoc.pipepager(doc.encode("UTF-8", 'replace'),
                         cmd='less -R')
     else:
         val = None
         try:
             val = display_option.stored_obj
             lh = LaunchHelper(GetCase)
             lh.run(val)
         except:
             raise Exception()
Example #48
0
    def input(self, prompt='>', hidden=False):
        """
        Get a choice from the user.
        """
        if len(self) > 10:
            long_ = True
            prompt = 'Type a number and press [ENTER]: '
        else: long_ = False
        if hidden == False:
            self.show_heading = True
            if len(self) + 4 > Cli.height():
                self.label = Cli.term_fx('bn', "Press 'q'") #make this work
                self.label += ', then make a choice (1-{})'.format(len(self))

                # can i use less() here?
                pydoc.pipepager(str(self), cmd='less -R')

            else: print(self) #pylint: disable=C0325
        else: write(self.label)

        if len(self) > 0:
            try:
                if long_:
                    sel_str = Cli.input(prompt)
                else: sel_str = Cli.get_keypress(prompt)
                if sel_str.isdigit():
                    sel = int(sel_str)
                else: sel = None
            except KeyboardInterrupt:
                print('') #pylint: disable=C0325
                return None

            while sel == None or sel > len(self) or sel < 1:
                try:
                    if (sel == None or sel < 1) and\
                        len(self) > 0 and len(self) < 10:
                        sel_str = Cli.get_keypress(prompt)
                    else:
                        sel_str = Cli.input(prompt)
                    if sel_str.isdigit():
                        sel = int(sel_str)
                    else: sel = None
                except KeyboardInterrupt:
                    print('') #pylint: disable=C0325
                    return None
            return sel
        else: return None
Example #49
0
def help_command(args):
    commands = get_commands(args.parser)
    parser = commands.get(args.command, args.parser)
    if sys.stdout.isatty():
        if os.system('(less -R) 2>/dev/null') == 0:
            return pydoc.pipepager(parser.format_help(), cmd='less -R')
    else:
        print parser.format_help()
Example #50
0
def less(*args, **kwargs):
    """
    *doesn't really work with files in subdirectories?  Should be tested.
    """
    if 'file_' in kwargs.keys():
        filename = kwargs['file_']
        with open(filename, 'r') as file_handler:
            text = file_handler.read()
            file_handler.close()
    elif len(args) > 0:
        text = ''
        for arg in args:
            text += (' ' + arg)
        text = text.lstrip()
    if os.path.exists('/usr/bin/less'):
        pydoc.pipepager(text, cmd='less -R')
    else: # does this work?
        pydoc.pager(text)
Example #51
0
File: util.py Project: mcarton/eg
def page_string(str_to_page, pager_cmd):
    """
    Page str_to_page via the pager.
    """
    # By default, we expect the command to be `less -R`. If that is the
    # pager_cmd, but they don't have less on their machine, odds are they're
    # just using the default value. In this case the pager will fail, so we'll
    # just go via pydoc.pager, which tries to do smarter checking that we don't
    # want to bother trying to replicate.
    use_fallback_page_function = False
    if pager_cmd is None:
        use_fallback_page_function = True
    elif pager_cmd == FLAG_FALLBACK:
        use_fallback_page_function = True

    if use_fallback_page_function:
        pydoc.pager(str_to_page)
    else:
        # Otherwise, obey the user.
        pydoc.pipepager(str_to_page, cmd=pager_cmd)
Example #52
0
def pager(text):
    """ Outputs large text via pager if terminal isn't high enough. """
    cols, rows = get_terminal_size()

    while text[-1] == "\n":
        text = text[:-1]

    try:
      import pymoji
      text = pymoji.replaceAliases(text, 1)
    except ImportError:
      pass

    if len(text.split("\n")) > rows - 1:
        try:
            pydoc.pipepager(text, cmd="less -R")
        except:
            print(text)
    else:
        print(text)
Example #53
0
    def less(cls, *args, **kwargs):
        '''doesn't really work with files in subdirectories'''
        if 'file' in kwargs.keys():
        #arg = arg.strip() 
        #if arg in os.listdir('/home/cjhorn/bin'): 
            filename = kwargs['file']
            with open(filename, 'r') as f:
                text = f.read()
                f.close()
            #print text
            #os.system('less ' + filename)# this
        elif len(args) > 0:
            text = args[0]
  
        #else: sys.exit() #text = arg
        try: pydoc.pipepager(text, cmd='less -R')
#                #os.system('echo "' + text + '"|less') # this
        except: 
            try: pydoc.pager(text)
            except: 
                try: os.system('echo "{}"|more'.format(text))
                except:
                    print(text)
                    cls.wait()
Example #54
0
def text_to_less(text, cmd='less -R'):
    pydoc.pipepager(text, cmd=cmd)
Example #55
0
def main():
    args = parse_args()

    # Set up logging
    ch = logging.StreamHandler(stdout)
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(ColoredFormatter("%(log_color)s%(message)s"))
    logger.addHandler(ch)

    # Defaults on files
    if args.list_var_sets:
        args.variable_files = []
    elif os.path.isfile(WHIZKERS_DEFAULTS):
        args.variable_files.insert(0, WHIZKERS_DEFAULTS)
    else:
        logger.warn("Default variables file %s not found. Skipping..."
                    % WHIZKERS_DEFAULTS)

    if not os.path.isfile(args.ignores_file):
        logger.warn("Ignores file %s not found. Skipping..."
                    % args.ignores_file)
        args.ignores_file = None

    try:
        whizker = Whizker(
            args.template_dir,
            args.dest_dir,
            args.var_set_dir,
            args.env_vars,
            args.variable_files,
            args.ignores_file,
            args.watch_command
        )
    except (FileNotFoundError, FileParseError) as e:
        logger.critical(e)
        exit(1)

    if args.list_var_sets:
        try:
            for var_set in whizker.var_sets:
                print(var_set)
        except ValueError as e:
            logger.critical(e)
            exit(1)

    elif args.diff:
        pipepager(
            ''.join(
                ''.join(
                    diff_colorify(line) for line in diff
                ) for diff in whizker.diff()
            ),
            cmd='less -R',
        )

    elif args.dry:
        logger.warning("Commencing dry run...")
        for dest, mode, result in whizker.render():
            logger.info("Successfully dry rendered \"%s\"" % dest)

    elif args.watch:
        logger.info("Starting watch...")
        whizker.watch()
        try:
            while True:
                sleep(1)
        except KeyboardInterrupt:
            whizker.stop_watch()
        whizker.join_watch()

    else:
        whizker.render_and_write()
Example #56
0
        from ThugAPI import *
        import PyV8
        THUG =  "jsrun(x, ua=x, l=y)  run conversation x through JS evaluation\n"
        THUG += "                     with ua=user agent (default to ua in request) "
        THUG += "and l=log length (0 = print all)\n"
        THUG += "                     retains window object and JS context\n"
        THUG += "jw(x)                handle the window object, eg jw('location')\n"
        THUG += "jseval(x )           evaluate x with PyV8 with new or existing context"
    except ImportError:
        THUG = ""

    from CTCore import *
    from CTConsole import *
    from pydoc import pipepager
    c = console()
    _pager = lambda text: pipepager(text, 'less -R -X -F')
    def pager(text):
        if len(text.splitlines()) > 20:
            _pager(text)
        else:
            print text

    import readline, rlcompleter
    readline.parse_and_bind('tab:complete')

    import sys
    import re

    HEADERREGEX1 = 'GET (?P<path>[^ ]+) .+?\n(?:.+\n)*(?:^Referer: (?P<referer>.+)\n)(?:.+\n)*(?:^Host: (?P<host>.+))'
    HEADERREGEX2 = 'GET (?P<path>[^ ]+) .+?\n(?:.+\n)*(?:.+\n)*(?:^Host: (?P<host>.+))'
    HEADER_RE1 = re.compile(HEADERREGEX1, re.M|re.I)
Example #57
0
def source(obj):
    """source of the obj."""
    try:
        pydoc.pipepager(inspect.getsource(obj), "less")
    except IOError:
        pass