Ejemplo n.º 1
0
def interactive(idx=0, DongleClass=RfCat, intro=''):
    global d
    import rflib.chipcon_nic as rfnic
    import atexit

    d = DongleClass(idx=idx)
    d.setModeIDLE()       # this puts the dongle into Idle mode
    atexit.register(cleanupInteractiveAtExit)

    gbls = globals()
    lcls = locals()

    try:
        import IPython.Shell
        ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls)
        print intro
        ipsh.mainloop(intro)

    except ImportError, e:
        try:
            from IPython.terminal.interactiveshell import TerminalInteractiveShell
            ipsh = TerminalInteractiveShell()
            ipsh.user_global_ns.update(gbls)
            ipsh.user_global_ns.update(lcls)
            ipsh.autocall = 2       # don't require parenthesis around *everything*.  be smart!
            ipsh.mainloop(intro)
        except ImportError, e:
            print e
            shell = code.InteractiveConsole(gbls)
            shell.interact(intro)
Ejemplo n.º 2
0
def dbg_interact(lcls, gbls):
    intro = "Let's interact!"
    try:
        import IPython.Shell
        ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls)
        print(intro)
        ipsh.mainloop()

    except ImportError as e:
        try:
            from IPython.terminal.interactiveshell import TerminalInteractiveShell
            ipsh = TerminalInteractiveShell()
            ipsh.user_global_ns.update(gbls)
            ipsh.user_global_ns.update(lcls)
            ipsh.autocall = 2       # don't require parenthesis around *everything*.  be smart!
            print(intro)
            ipsh.mainloop()
        except ImportError as e:
            try:
                from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
                ipsh = TerminalInteractiveShell()
                ipsh.user_global_ns.update(gbls)
                ipsh.user_global_ns.update(lcls)
                ipsh.autocall = 2       # don't require parenthesis around *everything*.  be smart!

                print(intro)
                ipsh.mainloop()
            except ImportError as e:
                print(e)
                shell = code.InteractiveConsole(gbls)
                print(intro)
                shell.interact()
Ejemplo n.º 3
0
def dbg_interact(lcls, gbls, intro=None):
    shelltype = STYPE_NONE

    if intro is None:
        intro = "Let's interact!"

    print(intro)
    try:
        from IPython import embed
        shelltype = STYPE_IPYTHON_NEW

    except ImportError as e:
        try:
            import IPython.Shell
            ipsh = IPython.Shell.IPShell(argv=[''],
                                         user_ns=lcls,
                                         user_global_ns=gbls)
            shelltype = STYPE_IPYTHON

        except ImportError as e:
            try:
                from IPython.terminal.interactiveshell import TerminalInteractiveShell
                ipsh = TerminalInteractiveShell()
                ipsh.user_global_ns.update(gbls)
                ipsh.user_global_ns.update(lcls)
                ipsh.autocall = 2  # don't require parenthesis around *everything*.  be smart!
                shelltype = STYPE_IPYTHON

            except ImportError as e:
                try:
                    from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
                    ipsh = TerminalInteractiveShell()
                    ipsh.user_global_ns.update(gbls)
                    ipsh.user_global_ns.update(lcls)
                    ipsh.autocall = 2  # don't require parenthesis around *everything*.  be smart!
                    shelltype = STYPE_IPYTHON

                except ImportError as e:
                    print(e)
                    shell = code.InteractiveConsole(gbls)
                    shelltype = STYPE_IPYTHON

    if shelltype == STYPE_IPYTHON_NEW:
        globals().update(gbls)
        locals().update(lcls)
        embed()

    elif shelltype == STYPE_IPYTHON:
        ipsh.mainloop()

    elif shelltype == STYPE_CODE_INTERACT:
        shell.interact()

    else:
        print("SORRY, NO INTERACTIVE OPTIONS AVAILABLE!!  wtfo?")
Ejemplo n.º 4
0
def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cto_tree.settings")
    try:
        if len(sys.argv) >= 2 and sys.argv[1] == '--plain':
            raise ImportError
        user_ns = locals()
        if has_ushell:
            app = UmengIPythonApp.instance()
            app.initialize()
            app.shell.user_ns.update(user_ns)
            sys.exit(app.start())
        else:
            from IPython.terminal.interactiveshell import TerminalInteractiveShell
            shell = TerminalInteractiveShell(user_ns=user_ns)
            shell.mainloop()
    except ImportError:
        import code
        shell = code.InteractiveConsole(locals=locals())
        shell.interact()
Ejemplo n.º 5
0
    def __call__(self):
        from IPython.terminal.prompts import Prompts, Token
        from IPython.terminal.interactiveshell import TerminalInteractiveShell

        token = self._token

        class RFQuackShellPrompts(Prompts):
            def in_prompt_tokens(self, cli=None):
                return [(Token, token), (Token.Prompt, '> ')]

        TerminalInteractiveShell.prompts_class = RFQuackShellPrompts
        shell = TerminalInteractiveShell()
        shell.autocall = 2
        shell.show_banner(self._banner)

        q = RFQuack(self._transport, shell)
        q.idle()
        shell.push(dict(q=q, rfquack_pb2=rfquack_pb2))

        shell.mainloop()
Ejemplo n.º 6
0
def interactive(idx=0, DongleClass=RfCat, intro=''):
    global d
    import rflib.chipcon_nic as rfnic
    import atexit

    d = DongleClass(idx=idx)
    d.setModeRX()       # this puts the dongle into receive mode
    atexit.register(cleanupInteractiveAtExit)

    gbls = globals()
    lcls = locals()

    try:
        import IPython.Shell
        ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls)
        print intro
        ipsh.mainloop(intro)

    except ImportError, e:
        try:
            from IPython.terminal.interactiveshell import TerminalInteractiveShell
            ipsh = TerminalInteractiveShell()
            ipsh.user_global_ns.update(gbls)
            ipsh.user_global_ns.update(lcls)
            ipsh.autocall = 2       # don't require parenthesis around *everything*.  be smart!
            ipsh.mainloop(intro)
        except ImportError, e:
            try:
                from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
                ipsh = TerminalInteractiveShell()
                ipsh.user_global_ns.update(gbls)
                ipsh.user_global_ns.update(lcls)
                ipsh.autocall = 2       # don't require parenthesis around *everything*.  be smart!
                ipsh.mainloop(intro)
            except ImportError, e:
                print e
                shell = code.InteractiveConsole(gbls)
                shell.interact(intro)
Ejemplo n.º 7
0
def main():
    url = sys.argv[1]
    context['url'] = url
    pkg = app.dispatch_url(url)
    context['pkg'] = pkg
    for item in pkg.to_dict().items():
        print '{} = {}'.format(*item)

    def prepare_readline():
        import os
        import readline
        import atexit

        readline.parse_and_bind('tab: complete')
        histfile = os.path.expanduser("~/.daenerys_history")

        try:
            readline.read_history_file(histfile)
        except IOError:
            pass

        def savehist(histfile):
            readline.write_history_file(histfile)

        atexit.register(savehist, histfile)
        del atexit

    try:
        from IPython.terminal.interactiveshell import TerminalInteractiveShell
        shell = TerminalInteractiveShell(user_ns=context)
        shell.mainloop()
    except ImportError:
        import code
        shell = code.InteractiveConsole(locals=context)
        shell.runcode(prepare_readline.__code__)
        shell.interact()
Ejemplo n.º 8
0
def interactive(port='/dev/ttyACM0', InterfaceClass=CanInterface, intro='', load_filename=None):
    global c
    import atexit

    c = InterfaceClass(port=port, load_filename=load_filename)
    atexit.register(cleanupInteractiveAtExit)

    gbls = globals()
    lcls = locals()

    try:
        import IPython.Shell
        ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls)
        print intro
        ipsh.mainloop(intro)

    except ImportError, e:
        try:
            from IPython.terminal.interactiveshell import TerminalInteractiveShell
            ipsh = TerminalInteractiveShell()
            ipsh.user_global_ns.update(gbls)
            ipsh.user_global_ns.update(lcls)
            ipsh.autocall = 2       # don't require parenthesis around *everything*.  be smart!
            ipsh.mainloop(intro)
        except ImportError, e:
            try:
                from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
                ipsh = TerminalInteractiveShell()
                ipsh.user_global_ns.update(gbls)
                ipsh.user_global_ns.update(lcls)
                ipsh.autocall = 2       # don't require parenthesis around *everything*.  be smart!
                ipsh.mainloop(intro)
            except ImportError, e:
                print e
                shell = code.InteractiveConsole(gbls)
                shell.interact(intro)
Ejemplo n.º 9
0
def interactive(idx=0, DongleClass=RfCat, intro=''):
    global d
    import rflib.chipcon_nic as rfnic
    import atexit

    d = DongleClass(idx=idx)
    d.setModeRX()  # this puts the dongle into receive mode
    atexit.register(cleanupInteractiveAtExit)

    gbls = globals()
    lcls = locals()

    shellfailed = False

    try:
        from IPython.terminal.interactiveshell import TerminalInteractiveShell
        ipsh = TerminalInteractiveShell()
        ipsh.user_global_ns.update(gbls)
        ipsh.user_global_ns.update(lcls)
        ipsh.autocall = 2  # don't require parenthesis around *everything*.  be smart!
        print(intro)
        ipsh.mainloop()
    except ImportError as e:
        shellfailed = True

    if shellfailed:
        try:
            import IPython.Shell
            ipsh = IPython.Shell.IPShell(argv=[''],
                                         user_ns=lcls,
                                         user_global_ns=gbls)
            print(intro)
            ipsh.mainloop()

        except ImportError as e:
            shellfailed = True

    if shellfailed:
        try:
            from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
            ipsh = TerminalInteractiveShell()
            ipsh.user_global_ns.update(gbls)
            ipsh.user_global_ns.update(lcls)
            ipsh.autocall = 2  # don't require parenthesis around *everything*.  be smart!

            print(intro)
            ipsh.mainloop()
        except ImportError as e:
            shellfailed = True

    if shellfailed:
        print("falling back to straight Python... (%r)" % e)
        shell = code.InteractiveConsole(gbls)
        print(intro)
        shell.interact()
Ejemplo n.º 10
0
def interact(lcls, gbls):
    shellexception = None

    try:
        from IPython.terminal.interactiveshell import TerminalInteractiveShell
        ipsh = TerminalInteractiveShell()
        ipsh.user_global_ns.update(gbls)
        ipsh.user_global_ns.update(lcls)
        ipsh.autocall = 2  # don't require parenthesis around *everything*.  be smart!
        ipsh.mainloop()
    except ImportError as e:
        shellexception = e

    if shellexception:
        try:
            import IPython.Shell
            ipsh = IPython.Shell.IPShell(argv=[''],
                                         user_ns=lcls,
                                         user_global_ns=gbls)
            ipsh.mainloop()

        except ImportError as e:
            shellexception = e

    if shellexception:
        try:
            from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
            ipsh = TerminalInteractiveShell()
            ipsh.user_global_ns.update(gbls)
            ipsh.user_global_ns.update(lcls)
            ipsh.autocall = 2  # don't require parenthesis around *everything*.  be smart!

            ipsh.mainloop()
        except ImportError as e:
            shellexception = e

    if shellexception:
        print("falling back to straight Python... (%r)" % shellexception)
        shell = code.InteractiveConsole(gbls)
        shell.interact()
Ejemplo n.º 11
0
def main():  # pylint: disable=too-many-statements

    # Set up a simple argument parser.
    parser = binhoArgumentParser(
        description="Convenience shell for working with Binho host adapters.")
    parser.add_argument(
        "-e",
        "--exec",
        metavar="code",
        type=str,
        help="Executes the provided code as though it were passed " +
        "to a Binho host adapter shell, and then terminates.",
        dest="code",
    )
    parser.add_argument(
        "-E",
        "--pre-exec",
        metavar="code",
        type=str,
        help="Executes the provided code as though it were passed " +
        "to a Binho host adapter shell, but does not explicitly terminate.",
        dest="prelude",
    )
    parser.add_argument(
        "-f",
        "--file",
        metavar="file",
        type=str,
        help="Executes the relevant file before starting the given shell.",
    )
    parser.add_argument(
        "-M",
        "--automagic",
        dest="automagic",
        action="store_true",
        help="Enable automagic, so lazy developers don't have to type %%.",
    )
    parser.add_argument(
        "-P",
        "--avoid-parens",
        dest="avoidparens",
        action="store_true",
        help=
        "Enable full autocall, so bare methods are executed, rather than printed.",
    )
    parser.add_argument(
        "-A",
        "--autoreload",
        dest="autoreload",
        action="store_true",
        help=
        "Attempts to reload python modules automatically as they change; so current objects import new \
              functionality. This may sometimes break your shell.",
    )
    parser.add_argument(
        "-S",
        "--singleton",
        dest="singleton",
        action="store_true",
        help=
        "Connect via a singleton that persists across device reconnects. Note: device state is not preserved.",
    )

    args = parser.parse_args()

    if args.singleton:
        connect_function = parser.get_singleton_for_specified_device
    else:
        connect_function = parser.find_specified_device

    binho = connect_function()

    if binho.inBootloaderMode:
        print(
            "{} found on {}, but it cannot be used now because it's in DFU mode"
            .format(binho.productName, binho.commPort))
        sys.exit(errno.ENODEV)

    elif binho.inDAPLinkMode:
        print(
            "{} found on {}, but it cannot be used now because it's in DAPlink mode"
            .format(binho.productName, binho.commPort))
        print("Tip: Exit DAPLink mode using 'binho daplink -q' command")
        sys.exit(errno.ENODEV)

    # Break into IPython for the shell.
    if not args.code:
        print(
            "Spawning an IPython shell for easy access to your Binho host adapter."
        )
        print(
            "Like normal python, you can use help(object) to get help for that object.\n"
        )

        print(
            "Try help(binho.gpio) to see the documentation for the Binho host adapter GPIO;"
        )
        print(
            "try dir(binho) to see a list of properties on the Binho Host Adapter object, and"
        )
        print(
            "try binho.available_interfaces() and binho.available_programmers() to see"
        )
        print(
            "the interfaces you can work with, and the programmers you can create.\n"
        )

        singleton_text = "singleton " if args.singleton else ""
        print(
            "A Binho host adapter {}object has been created for you as 'binho'. Have fun!\n"
            .format(singleton_text))

    # Create a new shell, and give it access to our created Binho object.
    shell = TerminalInteractiveShell()
    shell.push("binho")

    # Create nice aliases for our primary interfaces.
    # pylint: disable=unused-variable
    i2c = binho.i2c
    spi = binho.spi
    dac = binho.dac
    adc = binho.adc
    oneWire = binho.oneWire
    # uart = binho.uart
    gpio = binho.gpio
    # shell.push(('i2c', 'spi', 'adc', 'uart', 'gpio',))
    shell.push(("i2c", "spi", "gpio", "dac", "adc", "oneWire"))
    # pylint: enable=unused-variable

    # Make the autoreload extension available.
    shell.extension_manager.load_extension("autoreload")

    # Add our magic commands, to make execution more 'fun'.
    shell.register_magics(binhoShellMagics)

    # If the user has requested automagic, let them have their automagic.
    if args.automagic:
        shell.automagic = True

    # If we're in avoid parenthesis mode
    if args.avoidparens:
        shell.autocall = 2

    # If we're using autoreload, enable that.
    if args.autoreload:
        shell.run_cell("%autoreload 2")
        print(
            "Heads up: you've enabled autoreload. Things make break in unexpected ways as your code changes."
        )
        print(
            "You can fix this by adjusting your expectations regarding breakage.\n"
        )

    # Handle any inline execution requested.
    if args.code or args.prelude:

        # Replace any ;'s with newlines, so we can execute more than one
        # statement.
        code = args.code or args.prelude
        code = re.sub(r";\s*", "\n", code)
        lines = code.split("\n")

        # If we're in execute-and-quit mode, do so.

        for line in lines:
            shell.run_cell(line, shell_futures=True)

        # If we're to exit after running the relevant code, do so.
        if args.code:
            sys.exit(0)

    # If we have a file to execute, execute it.
    if args.file:
        shell.safe_execfile_ipy(args.file,
                                shell_futures=True,
                                raise_exceptions=True)

    # Run the shell itself.
    shell.connect_function = connect_function
    shell.mainloop()

    # close the connection to the device
    binho.close()
Ejemplo n.º 12
0
def console(**kwargs):
    """
    An REPL fully configured for experimentation.

    usage:
        blueberrypy console [options]

    options:
        -e ENVIRONMENT, --environment=ENVIRONMENT  apply the given config environment
        -C ENV_VAR_NAME, --env-var ENV_VAR_NAME    add the given config from environment variable name
                                                   [default: BLUEBERRYPY_CONFIG]
        --ipython                                  use IPython shell instead of Python one
        -h, --help                                 show this help message and exit

    """

    banner = """
*****************************************************************************
* If the configuration file you specified contains a [sqlalchemy_engine*]   *
* section, a default SQLAlchemy engine and session should have been created *
* for you automatically already.                                            *
*****************************************************************************
"""
    environment = kwargs.get("environment")
    config_dir = kwargs.get("config_dir")
    environment and cherrypy.config.update({"environment": environment})
    configuration = BlueberryPyConfiguration(
        config_dir=config_dir,
        environment=environment,
        env_var_name=kwargs.get('env_var'),
    )
    use_ipython = kwargs.get("ipython", False)
    package_name = shell.get_package_name(configuration)

    if use_ipython:
        try:
            from IPython.terminal.interactiveshell import TerminalInteractiveShell
        except ImportError as e:
            print(e)
            print("""Cannot import iPython. Did you install it?""")
            return
        try:
            app_package = import_module(package_name)
        except ImportError as e:
            print(e)
            app_package = None
        repl = TerminalInteractiveShell(
            user_ns=shell.get_user_namespace(configuration),
            user_module=app_package,
            display_completions='multicolumn',  # oldstyle is 'readlinelike'
            mouse_support=True,
            space_for_menu=10,  # reserve N lines for the completion menu
        )
        repl.show_banner(banner)
        repl.mainloop()
    else:
        try:
            import readline
        except ImportError as e:
            print(e)
        else:
            import rlcompleter
        sys.ps1 = "[%s]>>> " % package_name
        sys.ps2 = "[%s]... " % package_name

        ns = shell.get_user_namespace(configuration, include_pkg=True)
        repl = InteractiveConsole(locals=ns)
        repl.prompt = package_name
        repl.interact(banner)
Ejemplo n.º 13
0
def main():
    import optparse

    parser = optparse.OptionParser()
    # Shall we fuzz the request, response, or both?
    # Set via optparse in main
    global sr_request  # search/replace tuple for requests - (True, [search, replace]) where true means to use regex
    global sr_response  # search/replace tuple for responses - (True, [search, replace]) where true means to use regex
    global fuzz_request
    global fuzz_response

    # Other module-wide variables
    global debug
    global term
    global logger
    global fwdr

    parser.add_option("-l", "--local-addr", dest="local_addr", default="127.0.0.1", help="Local address to bind to")
    parser.add_option("-p", "--local-port", type="int", dest="local_port", default=1234, help="Local port to bind to")
    parser.add_option("-r", "--remote-addr", dest="remote_addr", help="Remote address to bind to")
    parser.add_option("-P", "--remote-port", type="int", dest="remote_port", default=80, help="Remote port to bind to")

    parser.add_option(
        "--search-request",
        dest="search_request",
        default="",
        help="String that if found will be replaced by --replace-request's value",
    )
    parser.add_option(
        "--replace-request", dest="replace_request", default="", help="String to replace the value of --search-request"
    )
    parser.add_option(
        "--search-response",
        dest="search_response",
        default="",
        help="String that if found will be replaced by --replace-request's value",
    )
    parser.add_option(
        "--replace-response",
        dest="replace_response",
        default="",
        help="String to replace the value of --search-request",
    )

    parser.add_option(
        "--regex-request",
        action="store_true",
        dest="request_use_regex",
        help="Requests: Use regular expressions for search and replace instead of string constants",
    )
    parser.add_option(
        "--regex-response",
        action="store_true",
        dest="response_use_regex",
        help="Responses: Use regular expressions for search and replace instead of string constants",
    )

    parser.add_option(
        "--fuzz-request",
        action="store_true",
        dest="fuzz_request",
        help="Fuzz the request which the proxy gets from the connecting client \
            prior to sending it to the remote host",
    )
    parser.add_option(
        "--fuzz-response",
        action="store_true",
        dest="fuzz_response",
        help="Fuzz the response which the proxy gets from the remote host prior \
            to sending it to the conecting client",
    )

    parser.add_option(
        "-i",
        "--run-info",
        dest="run_info",
        default="",
        help="Additional information string to add to database run_info entry",
    )

    parser.add_option(
        "-d",
        "--debug",
        type="int",
        dest="debug",
        default=0,
        help="Debug level (0-5, 0: No debugging; 1: Simple conneciton \
            information; 2: Simple data information; 3: Listener data display; 4: \
            Sender data display; 5: All data display)",
    )

    (options, args) = parser.parse_args()

    if not options.remote_addr or not options.remote_port:
        parser.print_help()
        exit(1)

    # Validate options for search/replace
    if (options.search_request and not options.replace_request) or (
        options.replace_request and not options.search_request
    ):
        print >> sys.stderr, "Both --search-request and --replace-request must be provided together"
        exit(1)

    if (options.search_response and not options.replace_response) or (
        options.replace_response and not options.search_response
    ):
        print >> sys.stderr, "Both --search-response and --replace-response must be provided together"
        exit(1)

    # Setup a TerminalController for formatted output
    term = TerminalController()

    # Print the current run information
    print (
        term.render(
            """\nSetting up asynch. TCP proxy with the following settings:
    ${GREEN}Local binding Address: %s
    Local binding Port:    %s${NORMAL}

    ${RED}Remote host address:   %s
    Remote host port:      %s${NORMAL}
    """
        )
        % (options.local_addr, options.local_port, options.remote_addr, options.remote_port)
    )

    # Set the debug value
    debug = options.debug

    # If run info was passed in on the command line, use that for the run_info table
    # additional info field (It will have what's being fuzzed prepended to it as well)
    run_additional_info = options.run_info

    # Print the selected debug value
    if debug > 0:
        if debug == 1:
            print ("    Debug: Level 1 (Show simple connection information)")
        elif debug == 2:
            print ("    Debug: Level 2 (Show simple data information, such as the size of sent/received messages)")
        elif debug == 3:
            print ("    Debug: Level 3 (Show listener data and size of sent/received messages)")
        elif debug == 4:
            print ("    Debug: Level 4 (Show sender data and size of sent/received messages)")
        elif debug == 5:
            print (
                "    Debug: Level 5 (Show all possible information, including the size of sent/received messages, and their data for listener and sender)"
            )
    print ("")

    # Display and setup search/replace things
    if options.search_request and options.replace_request:
        sr_request = [
            None,
            options.search_request.decode("string-escape"),
            options.replace_request.decode("string-escape"),
        ]
        # Check if we want to use regex instead of string constants
        if options.request_use_regex:
            # Use regex instead of string replace
            print (
                term.render(
                    "Running regex search/replace on ${BOLD}REQUESTS${NORMAL} with regex: 's/%s/%s'"
                    % (sr_request[1], sr_request[2])
                )
            )
            sr_request[0] = True
        else:
            print (
                term.render(
                    "Running string search/replace on ${BOLD}REQUESTS${NORMAL} with search/replace: 's/%s/%s'"
                    % (sr_request[1], sr_request[2])
                )
            )
            sr_request[0] = False
    else:
        sr_request = None

    if options.search_response and options.replace_response:
        sr_response = [
            None,
            options.search_response.decode("string-escape"),
            options.replace_response.decode("string-escape"),
        ]
        # Check if we want to use regex instead of string constants
        if options.response_use_regex:
            print (
                term.render(
                    "Running regex search/replace on ${BOLD}RESPONSES${NORMAL} with regex: 's/%s/%s'"
                    % (sr_response[1], sr_response[2])
                )
            )
            sr_response[0] = True
        else:
            print (
                term.render(
                    "Running string search/replace on ${BOLD}RESPONSES${NORMAL} with search/replace: 's/%s/%s'"
                    % (sr_response[1], sr_response[2])
                )
            )
            sr_response[0] = False
    else:
        sr_response = None

    # Setup which to fuzz - request, response, neither, both?
    if options.fuzz_request:
        fuzz_request = options.fuzz_request
        run_additional_info = "Fuzzing REQUESTS; " + run_additional_info
        print (term.render("Fuzzing ${BOLD}REQUESTS${NORMAL}"))
    else:
        fuzz_request = False

    if options.fuzz_response:
        fuzz_response = options.fuzz_response
        run_additional_info = "Fuzzing RESPONSES; " + run_additional_info
        print (term.render("Fuzzing ${BOLD}RESPONSES${NORMAL}"))
    else:
        fuzz_response = False

    if not (options.fuzz_response or options.fuzz_request):
        run_additional_info = "Fuzzing NONE; " + run_additional_info
        print (
            term.render(
                "Fuzzing ${BOLD}<NOTHING>${NORMAL} (Maybe you wanted ${BOLD}--fuzz-request or --fuzz-response${NORMAL}?)"
            )
        )

    if fuzz_request and fuzz_response:
        print (
            term.render(
                "${YELLOW}\nWARNING! WARNING!\n${BOLD}Fuzzing BOTH the request and response is probably a bad idea, ensure this is what you want to do!${NORMAL}${YELLOW}\nWARNING! WARNING!\n${NORMAL}"
            )
        )

    # host, db, username, passwd
    if logging_enabled:
        logger = postgresLogger("postgreshost", "dbname", "dbuser", "dbpass")

        logger.log_run_info("CompanyName", "ProjectName-v1.2.3", run_additional_info)

    # create object that spawns reciever/sender pairs upon connection
    fwdr = forwarder(options.local_addr, options.local_port, options.remote_addr, options.remote_port)
    print ("Listener running...")
    # asyncore.loop()

    # A quick hack to be able to control fuzz on/off while running
    # separate asyncore.loop into its own thread so we can have terminal control
    asyncThread = Thread(target=asyncore.loop)
    asyncThread.start()

    # start a console (ipython)
    from IPython.terminal.interactiveshell import TerminalInteractiveShell

    shell = TerminalInteractiveShell(user_ns=globals())
    shell.mainloop()

    # cleanup otherwise thread wont die and program hangs
    fwdr.close()
    # asyncore.close_all()
    asyncThread._Thread__stop()
Ejemplo n.º 14
0
def main():

    # Set up a simple argument parser.
    parser = GreatFETArgumentParser(
        description="Convenience shell for working with GreatFET devices.")
    parser.add_argument(
        '-e',
        '--exec',
        metavar="code",
        type=str,
        help="Executes the provided code as though it were passed " +
        "to a greatfet shell, and then terminates.",
        dest="code")
    parser.add_argument(
        '-E',
        '--pre-exec',
        metavar="code",
        type=str,
        help="Executes the provided code as though it were passed " +
        "to a greatfet shell, but does not explicitly terminate.",
        dest="prelude")
    parser.add_argument(
        '-f',
        '--file',
        metavar="file",
        type=str,
        help="Executes the relevant file before starting the given shell.")
    parser.add_argument(
        '-M',
        '--automagic',
        dest="automagic",
        action='store_true',
        help="Enable automagic, so lazy developers don't have to type %%.")
    parser.add_argument(
        '-P',
        '--avoid-parens',
        dest="avoidparens",
        action='store_true',
        help=
        "Enable full autocall, so bare methods are executed, rather than printed."
    )
    parser.add_argument(
        '-A',
        '--autoreload',
        dest="autoreload",
        action='store_true',
        help=
        "Attempts to reload python modules automatically as they change; so current objects import new functionality. This may sometimes break your shell."
    )
    parser.add_argument(
        '-S',
        '--singleton',
        dest="singleton",
        action='store_true',
        help=
        "Connect via a singleton that persists across device reconnects. Note: device state is not preserved."
    )

    args = parser.parse_args()

    if args.singleton:
        connect_function = parser.get_singleton_for_specified_device
    else:
        connect_function = parser.find_specified_device

    gf = connect_function()

    # Break into IPython for the shell.
    if not args.code:
        print(
            "Spawning an IPython shell for easy access to your GreatFET board."
        )
        print(
            "Like normal python, you can use help(object) to get help for that object.\n"
        )

        print(
            "Try help(gf.gpio) to see the documentation for the GreatFET GPIO;"
        )
        print(
            "try dir(gf) to see a list of properties on the GreatFET object, and"
        )
        print(
            "try gf.available_interfaces() and gf.available_programmers() to see"
        )
        print(
            "the interfaces you can work with, and the programmers you can create.\n"
        )

        print(
            "This GreatFET shell is *magical*. Try some of our IPython magics:\n"
        )
        print("\t %dmesg      -- prints the GreatFET's debug ring (log)")
        print("\t %reconnect  -- tries to reconnect to the current GreatFET")
        print(
            "\t %makeflash  -- when run from a firmware build dir, builds and flashes your GreatFET"
        )
        print(
            "\t %reload     -- tries to reload your host python code; useful with $PYTHONPATH"
        )
        print(
            "\t %refet      -- (not %reset) resets and reconnects to the current GreatFET"
        )
        print("\t                [hey, %reset was taken!]\n\n")

        singleton_text = "singleton " if args.singleton else ""
        print(
            "A GreatFET {}object has been created for you as 'gf'. Have fun!\n"
            .format(singleton_text))

    # Create a new shell, and give it access to our created GreatFET object.
    shell = TerminalInteractiveShell()
    shell.push('gf')

    # Create nice aliases for our primary interfaces.
    i2c = gf.i2c
    spi = gf.spi
    adc = gf.adc
    uart = gf.uart
    gpio = gf.gpio
    shell.push((
        'i2c',
        'spi',
        'adc',
        'uart',
        'gpio',
    ))

    # Make the autoreload extension available.
    shell.extension_manager.load_extension('autoreload')

    # Add our magic commands, to make execution more 'fun'.
    shell.register_magics(GreatFETShellMagics)

    # If the user has requested automagic, let them have their automagic.
    if args.automagic:
        shell.automagic = True

    # If we're in avoid parenthesis mode
    if args.avoidparens:
        shell.autocall = 2

    # If we're using autoreload, enable that.
    if args.autoreload:
        shell.run_cell('%autoreload 2')
        print(
            "Heads up: you've enabled autoreload. Things make break in unexpected ways as your code changes."
        )
        print(
            "You can fix this by adjusting your expectations regarding breakage.\n"
        )

    # Handle any inline execution requested.
    if args.code or args.prelude:

        # Replace any ;'s with newlines, so we can execute more than one statement.
        code = args.code or args.prelude
        code = re.sub(r";\s*", "\n", code)
        lines = code.split("\n")

        # If we're in execute-and-quit mode, do so.

        for line in lines:
            shell.run_cell(line, shell_futures=True)

        # If we're to exit after running the relevant code, do so.
        if args.code:
            sys.exit(0)

    # If we have a file to execute, execute it.
    if args.file:
        shell.safe_execfile_ipy(args.file,
                                shell_futures=True,
                                raise_exceptions=True)

    # Run the shell itself.
    shell.connect_function = connect_function
    shell.mainloop()
Ejemplo n.º 15
0
def main():
    import optparse
    parser = optparse.OptionParser()
    # Shall we fuzz the request, response, or both?
    # Set via optparse in main
    global sr_request   # search/replace tuple for requests - (True, [search, replace]) where true means to use regex
    global sr_response  # search/replace tuple for responses - (True, [search, replace]) where true means to use regex
    global fuzz_request
    global fuzz_response

    # Other module-wide variables
    global debug
    global term
    global logger
    global fwdr

    parser.add_option( '-l','--local-addr', dest='local_addr',default='127.0.0.1', help='Local address to bind to')
    parser.add_option( '-p','--local-port', type='int',dest='local_port',default=1234, help='Local port to bind to')
    parser.add_option( '-r','--remote-addr',dest='remote_addr', help='Remote address to bind to')
    parser.add_option( '-P','--remote-port', type='int',dest='remote_port',default=80, help='Remote port to bind to')

    parser.add_option( '--search-request', dest='search_request',default='', help='String that if found will be replaced by --replace-request\'s value')
    parser.add_option( '--replace-request', dest='replace_request',default='', help='String to replace the value of --search-request')
    parser.add_option( '--search-response', dest='search_response',default='', help='String that if found will be replaced by --replace-request\'s value')
    parser.add_option( '--replace-response', dest='replace_response',default='', help='String to replace the value of --search-request')

    parser.add_option( '--regex-request', action='store_true' ,dest='request_use_regex', help='Requests: Use regular expressions for search and replace instead of string constants')
    parser.add_option( '--regex-response', action='store_true' ,dest='response_use_regex', help='Responses: Use regular expressions for search and replace instead of string constants')

    parser.add_option( '--fuzz-request', action='store_true' ,dest='fuzz_request', help='Fuzz the request which the proxy gets from the connecting client \
            prior to sending it to the remote host')
    parser.add_option( '--fuzz-response', action='store_true' ,dest='fuzz_response', help='Fuzz the response which the proxy gets from the remote host prior \
            to sending it to the conecting client')

    parser.add_option( '-i','--run-info', dest='run_info',default='', help='Additional information string to add to database run_info entry')

    parser.add_option( '-d','--debug', type='int',dest='debug',default=0, help='Debug level (0-5, 0: No debugging; 1: Simple conneciton \
            information; 2: Simple data information; 3: Listener data display; 4: \
            Sender data display; 5: All data display)')

    (options, args) = parser.parse_args()

    if not options.remote_addr or not options.remote_port:
        parser.print_help()
        exit(1)

    # Validate options for search/replace
    if (options.search_request and not options.replace_request) or (options.replace_request and not options.search_request):
        print >>sys.stderr, "Both --search-request and --replace-request must be provided together"
        exit(1)

    if (options.search_response and not options.replace_response) or (options.replace_response and not options.search_response):
        print >>sys.stderr, "Both --search-response and --replace-response must be provided together"
        exit(1)

    # Setup a TerminalController for formatted output
    term = TerminalController()

    # Print the current run information
    print(term.render("""\nSetting up asynch. TCP proxy with the following settings:
    ${GREEN}Local binding Address: %s
    Local binding Port:    %s${NORMAL}

    ${RED}Remote host address:   %s
    Remote host port:      %s${NORMAL}
    """) % (options.local_addr, options.local_port, options.remote_addr, options.remote_port))

    # Set the debug value
    debug = options.debug

    # If run info was passed in on the command line, use that for the run_info table
    # additional info field (It will have what's being fuzzed prepended to it as well)
    run_additional_info = options.run_info

    # Print the selected debug value
    if(debug > 0):
        if(debug == 1):
            print("    Debug: Level 1 (Show simple connection information)")
        elif(debug == 2):
            print("    Debug: Level 2 (Show simple data information, such as the size of sent/received messages)")
        elif(debug == 3):
            print("    Debug: Level 3 (Show listener data and size of sent/received messages)")
        elif(debug == 4):
            print("    Debug: Level 4 (Show sender data and size of sent/received messages)")
        elif(debug == 5):
            print("    Debug: Level 5 (Show all possible information, including the size of sent/received messages, and their data for listener and sender)")
    print("")

    # Display and setup search/replace things
    if options.search_request and options.replace_request:
        sr_request = [None, options.search_request.decode('string-escape'), options.replace_request.decode('string-escape')]
        # Check if we want to use regex instead of string constants
        if options.request_use_regex:
            # Use regex instead of string replace
            print(term.render("Running regex search/replace on ${BOLD}REQUESTS${NORMAL} with regex: 's/%s/%s'" % (sr_request[1], sr_request[2])))
            sr_request[0] = True
        else:
            print(term.render("Running string search/replace on ${BOLD}REQUESTS${NORMAL} with search/replace: 's/%s/%s'" % (sr_request[1], sr_request[2])))
            sr_request[0] = False
    else:
        sr_request = None

    if options.search_response and options.replace_response:
        sr_response = [None, options.search_response.decode('string-escape'), options.replace_response.decode('string-escape')]
        # Check if we want to use regex instead of string constants
        if options.response_use_regex:
            print(term.render("Running regex search/replace on ${BOLD}RESPONSES${NORMAL} with regex: 's/%s/%s'" % (sr_response[1], sr_response[2])))
            sr_response[0] = True
        else:
            print(term.render("Running string search/replace on ${BOLD}RESPONSES${NORMAL} with search/replace: 's/%s/%s'" % (sr_response[1], sr_response[2])))
            sr_response[0] = False
    else:
        sr_response = None

    # Setup which to fuzz - request, response, neither, both?
    if(options.fuzz_request):
        fuzz_request = options.fuzz_request
        run_additional_info = "Fuzzing REQUESTS; " + run_additional_info
        print(term.render("Fuzzing ${BOLD}REQUESTS${NORMAL}"))
    else:
        fuzz_request = False

    if(options.fuzz_response):
        fuzz_response = options.fuzz_response
        run_additional_info = "Fuzzing RESPONSES; " + run_additional_info
        print(term.render("Fuzzing ${BOLD}RESPONSES${NORMAL}"))
    else:
        fuzz_response = False

    if(not(options.fuzz_response or options.fuzz_request)):
        run_additional_info = "Fuzzing NONE; " + run_additional_info
        print(term.render("Fuzzing ${BOLD}<NOTHING>${NORMAL} (Maybe you wanted ${BOLD}--fuzz-request or --fuzz-response${NORMAL}?)"))

    if(fuzz_request and fuzz_response):
        print(term.render("${YELLOW}\nWARNING! WARNING!\n${BOLD}Fuzzing BOTH the request and response is probably a bad idea, ensure this is what you want to do!${NORMAL}${YELLOW}\nWARNING! WARNING!\n${NORMAL}"))

    # host, db, username, passwd
    if logging_enabled:
        logger = postgresLogger("postgreshost", "dbname", "dbuser", "dbpass")

        logger.log_run_info("CompanyName", "ProjectName-v1.2.3", run_additional_info)

    # create object that spawns reciever/sender pairs upon connection
    fwdr = forwarder(options.local_addr,options.local_port,options.remote_addr,options.remote_port)
    print("Listener running...")
    #asyncore.loop()

    # A quick hack to be able to control fuzz on/off while running
    # separate asyncore.loop into its own thread so we can have terminal control
    asyncThread = Thread(target=asyncore.loop)
    asyncThread.start()

    # start a console (ipython)
    from IPython.terminal.interactiveshell import TerminalInteractiveShell
    shell = TerminalInteractiveShell(user_ns=globals())
    shell.mainloop()

    # cleanup otherwise thread wont die and program hangs
    fwdr.close()
    #asyncore.close_all()
    asyncThread._Thread__stop()