コード例 #1
0
class UI:
    def __init__(self):
        self._console = Console()
        self._console.show_cursor(False)
        self._console.clear()
        t = self._create_table()
        self._console.print(t)

    def _create_table(self) -> Table:
        table = Table(title="Active Proximity ID's", box=SQUARE)
        table.add_column("Proximity ID")
        table.add_column("Address")
        table.add_column("RSSI")
        table.add_column("Active")
        return table

    def show(self, data: Dict[str, Element]):
        t = self._create_table()
        for k, el in data.items():
            t.add_row(
                k,
                el.address,
                f"{str(el.rssi)}dBm",
                f"{str(int(el.last_ts - el.first_ts))}s",
            )

        self._console.clear()
        self._console.print(t)

    def fin(self):
        self._console.show_cursor(True)
コード例 #2
0
ファイル: test_console.py プロジェクト: xyera/rich
def test_show_cursor():
    console = Console(file=io.StringIO(),
                      force_terminal=True,
                      legacy_windows=False)
    console.show_cursor(False)
    console.print("foo")
    console.show_cursor(True)
    assert console.file.getvalue() == "\x1b[?25lfoo\n\x1b[?25h"
コード例 #3
0
async def scan_for_targets():
    """Scan for targets, return json."""
    console = Console()
    console.clear()
    console.show_cursor(False)
    airmon = pyrcrack.AirmonNg()
    interfaces = await airmon.interfaces
    console.print(interfaces.table)
    interface = Prompt.ask('Select an interface',
                           choices=[a.interface for a in interfaces])

    async with airmon(interface) as mon:
        async with pyrcrack.AirodumpNg() as pdump:
            # TODO: Maybe copy this object upon __call__ so we can do, paralell
            # async for result in pdump(foo) (the only relevant part would be
            # execn properties) within the same temporary path?
            async for aps in pdump(mon.monitor_interface):
                console.clear()
                console.print(aps.table)
                client = Prompt.ask(
                    'Select an AP',
                    choices=['continue', *[str(a) for a in range(len(aps))]])

                if client != 'continue':
                    break

        async with pyrcrack.AirodumpNg() as pdump:
            console.print(
                ":vampire:",
                f"Selected client: [red] {aps[int(client)].bssid} [/red]")

            async for result in pdump(mon.monitor_interface,
                                      **aps[int(client)].airodump):
                console.clear()
                console.print(result.table)
                await asyncio.sleep(3)
コード例 #4
0
def hermes(args: Optional[List[str]] = None) -> None:
    """HermesPy Command Line Interface.

    Default entry point to execute hermespy `.yml` files via terminals.

    Args:

        args ([List[str], optional):
            Command line arguments.
            By default, the system argument vector will be interpreted.
    """

    # Recover command line arguments from system if none are provided
    if args is None:
        args = sys.argv[1:]

    parser = argparse.ArgumentParser(
        description='HermesPy - The Heterogeneous Mobile Radio Simulator',
        prog='hermes')
    parser.add_argument(
        "-p",
        help="settings directory from which to read the configuration",
        type=str)
    parser.add_argument(
        "-o",
        help="output directory to which results will be dumped",
        type=str)
    parser.add_argument("-s", help="style of result plots", type=str)
    parser.add_argument('-t',
                        '--test',
                        action='store_true',
                        help='run in test-mode, does not dump results')
    parser.add_argument('-l',
                        '--log',
                        action='store_true',
                        help='log the console information to a txt file')

    arguments = parser.parse_args(args)
    input_parameters_dir = arguments.p
    results_dir = arguments.o
    style = arguments.s

    # Create console
    console = Console(record=arguments.log)
    console.show_cursor(False)

    # Draw welcome header
    console.print(
        "\n[bold green]Welcome to HermesPy - The Heterogeneous Radio Mobile Simulator\n"
    )

    console.print(f"Version: {__version__}")
    console.print(f"Maintainer: {__maintainer__}")
    console.print(f"Contact: {__email__}")

    console.print(
        "\nFor detailed instructions, refer to the documentation https://barkhausen-institut.github.io/hermespy"
    )
    console.print(
        "Please report any bugs to https://github.com/Barkhausen-Institut/hermespy/issues\n"
    )

    # Validate command line parameters
    if not input_parameters_dir:
        input_parameters_dir = os.path.join(os.getcwd(), '_settings')

    elif not (os.path.isabs(input_parameters_dir)):
        input_parameters_dir = os.path.join(os.getcwd(), input_parameters_dir)

    console.log(f"Configuration will be read from '{input_parameters_dir}'")

    with console.status("Initializing Environment...", spinner='dots'):

        ##################
        # Import executable from YAML config dump
        factory = Factory()

        try:

            # Load serializable objects from configuration files
            serializables: List[Serializable] = factory.load(
                input_parameters_dir)

            # Filter out non-executables from the serialization list
            executables: List[Executable] = [
                s for s in serializables if isinstance(s, Executable)
            ]

            # Abort execution if no executable was found
            if len(executables) < 1:

                console.log(
                    "No executable routine was detected, aborting execution",
                    style="red")
                exit(-1)

            # For now, only single executables are supported
            executable = executables[0]

            # Configure executable
            if results_dir is None:
                executable.results_dir = Executable.default_results_dir()

            else:
                executable.results_dir = results_dir

        except ConstructorError as error:

            print(
                "\nYAML import failed during parsing of line {} in file '{}':\n\t{}"
                .format(error.problem_mark.line,
                        error.problem_mark.name,
                        error.problem,
                        file=sys.stderr))
            exit(-1)

        # Configure console
        executable.console = console

        # Configure style
        if style is not None:
            executable.style = style

        # Inform about the results directory
        console.log("Results will be saved in '{}'".format(
            executable.results_dir))

        # Dump current configuration to results directory
        if not arguments.test:
            shutil.copytree(input_parameters_dir,
                            executable.results_dir,
                            dirs_exist_ok=True)

    ##################
    # run simulation
    executable.execute()

    ###########
    # Goodbye :)
    console.log('Configuration executed. Goodbye.')

    # Save log
    if arguments.log:
        console.save_text(os.path.join(executable.results_dir, 'log.txt'))
コード例 #5
0
BEAT_TIME = 0.05


@contextmanager
def beat(length: int = 1) -> None:
    with console:
        console.clear()
        yield
    time.sleep(length * BEAT_TIME)


table = Table(show_footer=False)


console.clear()
console.show_cursor(False)
try:

    table.add_column("Release Date", no_wrap=True)
    with beat(10):
        console.print(table, justify="center")

    table.add_column("Title", Text.from_markup("[b]Total", justify="right"))
    with beat(10):
        console.print(table, justify="center")

    table.add_column("Budget", "[u]$412,000,000", no_wrap=True)
    with beat(10):
        console.print(table, justify="center")

    table.add_column("Opening Weekend", "[u]$577,703,455", no_wrap=True)
コード例 #6
0
def test_show_cursor():
    console = Console(file=io.StringIO())
    console.show_cursor(False)
    console.print("foo")
    console.show_cursor(True)
    assert console.file.getvalue() == "\x1b[?25lfoo\n\x1b[?25h"