예제 #1
0
def main(args, file=sys.stdout):  #pylint: disable=redefined-builtin
    _logging.configure_logging(args)

    if len(args) > 0 and args[0] == '--version':
        show_version_info_exit(file)

    azure_folder = os.path.expanduser('~/.azure')
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = Configuration(args)
    APPLICATION.initialize(config)

    try:
        cmd_result = APPLICATION.execute(args)
        # Commands can return a dictionary/list of results
        # If they do, we print the results.
        if cmd_result and cmd_result.result:
            formatter = OutputProducer.get_formatter(
                APPLICATION.configuration.output_format)
            OutputProducer(formatter=formatter, file=file).out(cmd_result)
    except Exception as ex:  # pylint: disable=broad-except
        log_telemetry('Error', log_type='trace')
        error_code = handle_exception(ex)
        return error_code
예제 #2
0
파일: main.py 프로젝트: Azure/azure-cli
def main(args, file=sys.stdout): #pylint: disable=redefined-builtin
    _logging.configure_logging(args)

    if len(args) > 0 and args[0] == '--version':
        show_version_info_exit(file)

    azure_folder = os.path.expanduser('~/.azure')
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = Configuration(args)
    APPLICATION.initialize(config)

    try:
        cmd_result = APPLICATION.execute(args)
        # Commands can return a dictionary/list of results
        # If they do, we print the results.
        if cmd_result and cmd_result.result:
            from azure.cli.core._output import OutputProducer
            formatter = OutputProducer.get_formatter(APPLICATION.configuration.output_format)
            OutputProducer(formatter=formatter, file=file).out(cmd_result)
    except Exception as ex: # pylint: disable=broad-except
        from azure.cli.core.telemetry import log_telemetry
        log_telemetry('Error', log_type='trace')
        error_code = handle_exception(ex)
        return error_code
예제 #3
0
def main():
    """ the main function """

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = CONFIGURATION

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        APPLICATION.execute(["configure"])
        print("When in doubt, ask for 'help'")
        config.firsttime()

    shell_app = Shell(
        completer=AZCOMPLETER,
        lexer=AzLexer,
        history=FileHistory(os.path.join(CONFIGURATION.get_config_dir(), config.get_history())),
        app=APPLICATION,
        # cli_config=os.path.join(azure_folder, 'config')
    )
    shell_app.run()
예제 #4
0
    def __init__(self, **kwargs):
        super(AzCli, self).__init__(**kwargs)

        from azure.cli.core.commands.arm import (
            register_ids_argument, register_global_subscription_argument)
        from azure.cli.core.cloud import get_active_cloud
        from azure.cli.core.commands.transform import register_global_transforms
        from azure.cli.core._session import ACCOUNT, CONFIG, SESSION

        from knack.util import ensure_dir

        self.data['headers'] = {}
        self.data['command'] = 'unknown'
        self.data['command_extension_name'] = None
        self.data['completer_active'] = ARGCOMPLETE_ENV_NAME in os.environ
        self.data['query_active'] = False

        azure_folder = self.config.config_dir
        ensure_dir(azure_folder)
        ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
        CONFIG.load(os.path.join(azure_folder, 'az.json'))
        SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)
        self.cloud = get_active_cloud(self)
        logger.debug('Current cloud config:\n%s', str(self.cloud.name))

        register_global_transforms(self)
        register_global_subscription_argument(self)
        register_ids_argument(self)  # global subscription must be registered first!

        self.progress_controller = None
def get_cli_profile():
    """Return a CLI profile class.

    *Disclaimer*: This method is not working for azure-cli-core>=2.21.0 (released in March 2021).

    .. versionadded:: 1.1.6

    .. deprecated:: 1.1.28

    :return: A CLI Profile
    :rtype: azure.cli.core._profile.Profile
    :raises: ImportError if azure-cli-core package is not available
    """

    try:
        from azure.cli.core._profile import Profile
        from azure.cli.core._session import ACCOUNT
        from azure.cli.core._environment import get_config_dir
    except ImportError:
        raise ImportError(
            "The public API of azure-cli-core has been deprecated starting 2.21.0, "
            + "and this method can no longer return a profile. " +
            "If you need to load CLI profile using this method, you need to install 'azure-cli-core<2.21.0'. "
            +
            "You may corrupt data if you use current CLI and old azure-cli-core."
        )

    azure_folder = get_config_dir()
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    return Profile(storage=ACCOUNT)
예제 #6
0
    def _get_azure_cli_auth_token() -> dict:
        """
        Try to get the az cli authenticated token
        :return: refresh token
        """
        import os

        try:
            # this makes it cleaner, but in case azure cli is not present on virtual env,
            # but cli exists on computer, we can try and manually get the token from the cache
            from azure.cli.core._profile import Profile
            from azure.cli.core._session import ACCOUNT
            from azure.cli.core._environment import get_config_dir

            azure_folder = get_config_dir()
            ACCOUNT.load(os.path.join(azure_folder, "azureProfile.json"))
            profile = Profile(storage=ACCOUNT)
            token_data = profile.get_raw_token()[0][2]

            return token_data

        except ModuleNotFoundError:
            try:
                import os
                import json

                folder = os.getenv("AZURE_CONFIG_DIR", None) or os.path.expanduser(os.path.join("~", ".azure"))
                token_path = os.path.join(folder, "accessTokens.json")
                with open(token_path) as f:
                    data = json.load(f)

                # TODO: not sure I should take the first
                return data[0]
            except Exception as e:
                raise KustoClientError("Azure cli token was not found. Please run 'az login' to setup account.", e)
예제 #7
0
def main(style=None):
    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = SHELL_CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    if style:
        given_style = style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style_obj = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        print("When in doubt, ask for 'help'")
        config.firsttime()

    shell_app = Shell(completer=AZCOMPLETER,
                      lexer=AzLexer,
                      history=FileHistory(
                          os.path.join(shell_config_dir(),
                                       config.get_history())),
                      app=APPLICATION,
                      styles=style_obj)
    shell_app.run()
예제 #8
0
def main(args, file=sys.stdout):  # pylint: disable=redefined-builtin
    azlogging.configure_logging(args)
    logger.debug('Command arguments %s', args)

    if len(args) > 0 and args[0] == '--version':
        show_version_info_exit(file)

    azure_folder = get_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    APPLICATION.initialize(Configuration())

    try:
        cmd_result = APPLICATION.execute(args)

        # Commands can return a dictionary/list of results
        # If they do, we print the results.
        if cmd_result and cmd_result.result is not None:
            from azure.cli.core._output import OutputProducer
            formatter = OutputProducer.get_formatter(APPLICATION.configuration.output_format)
            OutputProducer(formatter=formatter, file=file).out(cmd_result)

    except Exception as ex:  # pylint: disable=broad-except

        # TODO: include additional details of the exception in telemetry
        telemetry.set_exception(ex, 'outer-exception',
                                'Unexpected exception caught during application execution.')
        telemetry.set_failure()

        error_code = handle_exception(ex)
        return error_code
예제 #9
0
    def __init__(self, **kwargs):
        super(AzCli, self).__init__(**kwargs)

        from azure.cli.core.commands import register_cache_arguments
        from azure.cli.core.commands.arm import (
            register_ids_argument, register_global_subscription_argument)
        from azure.cli.core.cloud import get_active_cloud
        from azure.cli.core.commands.transform import register_global_transforms
        from azure.cli.core._session import ACCOUNT, CONFIG, SESSION, INDEX

        from knack.util import ensure_dir

        self.data['headers'] = {}
        self.data['command'] = 'unknown'
        self.data['command_extension_name'] = None
        self.data['completer_active'] = ARGCOMPLETE_ENV_NAME in os.environ
        self.data['query_active'] = False

        azure_folder = self.config.config_dir
        ensure_dir(azure_folder)
        ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
        CONFIG.load(os.path.join(azure_folder, 'az.json'))
        SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)
        INDEX.load(os.path.join(azure_folder, 'commandIndex.json'))

        self.cloud = get_active_cloud(self)
        logger.debug('Current cloud config:\n%s', str(self.cloud.name))
        self.local_context = AzCLILocalContext(self)
        register_global_transforms(self)
        register_global_subscription_argument(self)
        register_ids_argument(
            self)  # global subscription must be registered first!
        register_cache_arguments(self)

        self.progress_controller = None
예제 #10
0
    def __init__(self, **kwargs):
        super(AzCli, self).__init__(**kwargs)

        from azure.cli.core.commands.arm import add_id_parameters, register_global_subscription_parameter
        from azure.cli.core.cloud import get_active_cloud
        from azure.cli.core.extensions import register_extensions
        from azure.cli.core._session import ACCOUNT, CONFIG, SESSION

        import knack.events as events
        from knack.util import ensure_dir

        self.data['headers'] = {}
        self.data['command'] = 'unknown'
        self.data['command_extension_name'] = None
        self.data['completer_active'] = ARGCOMPLETE_ENV_NAME in os.environ
        self.data['query_active'] = False

        azure_folder = self.config.config_dir
        ensure_dir(azure_folder)
        ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
        CONFIG.load(os.path.join(azure_folder, 'az.json'))
        SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)
        self.cloud = get_active_cloud(self)
        logger.debug('Current cloud config:\n%s', str(self.cloud.name))

        register_extensions(self)
        self.register_event(events.EVENT_INVOKER_POST_CMD_TBL_CREATE,
                            add_id_parameters)
        register_global_subscription_parameter(self)

        self.progress_controller = None
예제 #11
0
    def cli_execute(self, cmd):
        try:
            args = parse_quotes(cmd)
            azlogging.configure_logging(args)

            azure_folder = get_config_dir()
            if not os.path.exists(azure_folder):
                os.makedirs(azure_folder)
            ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
            CONFIG.load(os.path.join(azure_folder, 'az.json'))
            SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

            config = Configuration(args)
            self.app.initialize(config)

            result = self.app.execute(args)
            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.out(result)
                else:
                    formatter = OutputProducer.get_formatter(
                        self.app.configuration.output_format)
                    OutputProducer(formatter=formatter,
                                   file=sys.stdout).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
예제 #12
0
    def cli_execute(self, cmd):
        """ sends the command to the CLI to be executed """

        try:
            args = parse_quotes(cmd)

            if args and args[0] == 'feedback':
                self.config.set_feedback('yes')
                self.user_feedback = False

            azure_folder = get_config_dir()
            if not os.path.exists(azure_folder):
                os.makedirs(azure_folder)
            ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
            CONFIG.load(os.path.join(azure_folder, 'az.json'))
            SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

            invocation = self.cli_ctx.invocation_cls(
                cli_ctx=self.cli_ctx,
                parser_cls=self.cli_ctx.parser_cls,
                commands_loader_cls=self.cli_ctx.commands_loader_cls,
                help_cls=self.cli_ctx.help_cls)

            if '--progress' in args:
                args.remove('--progress')
                execute_args = [args]
                thread = Thread(target=invocation.execute, args=execute_args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                self.curr_thread = thread

                progress_args = [self]
                thread = Thread(target=progress_view, args=progress_args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                result = None
            else:
                result = invocation.execute(args)

            self.last_exit = 0
            if result and result.result is not None:
                if self.output:
                    self.output.write(result)
                    self.output.flush()
                else:
                    formatter = self.cli_ctx.output.get_formatter(
                        self.cli_ctx.invocation.data['output'])
                    self.cli_ctx.output.out(result,
                                            formatter=formatter,
                                            out_file=sys.stdout)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
예제 #13
0
def initialize_client():
    azure_folder = get_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    APPLICATION.initialize(Configuration())
예제 #14
0
파일: app.py 프로젝트: jiayexie/azure-cli
    def cli_execute(self, cmd):
        """ sends the command to the CLI to be executed """

        try:
            args = parse_quotes(cmd)

            if args and args[0] == 'feedback':
                self.config.set_feedback('yes')
                self.user_feedback = False

            azure_folder = get_config_dir()
            if not os.path.exists(azure_folder):
                os.makedirs(azure_folder)
            ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
            CONFIG.load(os.path.join(azure_folder, 'az.json'))
            SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

            invocation = self.cli_ctx.invocation_cls(cli_ctx=self.cli_ctx,
                                                     parser_cls=self.cli_ctx.parser_cls,
                                                     commands_loader_cls=self.cli_ctx.commands_loader_cls,
                                                     help_cls=self.cli_ctx.help_cls)

            if '--progress' in args:
                args.remove('--progress')
                execute_args = [args]
                thread = Thread(target=invocation.execute, args=execute_args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                self.curr_thread = thread

                progress_args = [self]
                thread = Thread(target=progress_view, args=progress_args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                result = None
            else:
                result = invocation.execute(args)

            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.write(result)
                    self.output.flush()
                else:
                    formatter = OutputProducer.get_formatter(self.cli_ctx.invocation.data['output'])
                    OutputProducer(formatter=formatter).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
예제 #15
0
    def cli_execute(self, cmd):
        """ sends the command to the CLI to be executed """

        try:
            args = parse_quotes(cmd)
            azlogging.configure_logging(args)

            if len(args) > 0 and args[0] == 'feedback':
                SHELL_CONFIGURATION.set_feedback('yes')
                self.user_feedback = False

            azure_folder = get_config_dir()
            if not os.path.exists(azure_folder):
                os.makedirs(azure_folder)
            ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
            CONFIG.load(os.path.join(azure_folder, 'az.json'))
            SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

            self.app.initialize(Configuration())

            if '--progress' in args:
                args.remove('--progress')
                thread = ExecuteThread(self.app.execute, args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                self.curr_thread = thread

                thread = ProgressViewThread(progress_view, self)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                result = None

            else:
                result = self.app.execute(args)

            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.write(result)
                    self.output.flush()
                else:
                    formatter = OutputProducer.get_formatter(
                        self.app.configuration.output_format)
                    OutputProducer(formatter=formatter,
                                   file=self.output).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
예제 #16
0
def main(style=None):
    if APPLICATION.session["az_interactive_active"]:
        logger.warning("You're in the interactive shell already.\n")
        return

    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = azclishell.configuration.CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    try:
        commands = GatherCommands()
        az_completer = AzCompleter(commands)
    except IOError:  # if there is no cache
        az_completer = None

    if style:
        given_style = style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style_obj = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        config.firsttime()

    ask_feedback = False
    if not config.has_feedback() and frequent_user:
        print("\n\nAny comments or concerns? You can use the \'feedback\' command!" +
              " We would greatly appreciate it.\n")
        ask_feedback = True

    shell_app = Shell(
        completer=az_completer,
        lexer=AzLexer,
        history=FileHistory(
            os.path.join(shell_config_dir(), config.get_history())),
        app=APPLICATION,
        styles=style_obj,
        user_feedback=ask_feedback
    )
    shell_app.app.session["az_interactive_active"] = True
    shell_app.run()
    shell_app.app.session["az_interactive_active"] = False
def main(style=None):
    if APPLICATION.session["az_interactive_active"]:
        logger.warning("You're in the interactive shell already.\n")
        return

    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = azclishell.configuration.CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    try:
        commands = GatherCommands()
        az_completer = AzCompleter(commands)
    except IOError:  # if there is no cache
        az_completer = None

    if style:
        given_style = style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style_obj = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        config.firsttime()

    ask_feedback = False
    if not config.has_feedback() and frequent_user:
        print(
            "\n\nAny comments or concerns? You can use the \'feedback\' command!"
            + " We would greatly appreciate it.\n")
        ask_feedback = True

    shell_app = Shell(completer=az_completer,
                      lexer=AzLexer,
                      history=FileHistory(
                          os.path.join(shell_config_dir(),
                                       config.get_history())),
                      app=APPLICATION,
                      styles=style_obj,
                      user_feedback=ask_feedback)
    shell_app.app.session["az_interactive_active"] = True
    shell_app.run()
    shell_app.app.session["az_interactive_active"] = False
예제 #18
0
    def cli_execute(self, cmd):
        """ sends the command to the CLI to be executed """

        try:
            args = parse_quotes(cmd)
            azlogging.configure_logging(args)

            if len(args) > 0 and args[0] == 'feedback':
                SHELL_CONFIGURATION.set_feedback('yes')
                self.user_feedback = False

            azure_folder = get_config_dir()
            if not os.path.exists(azure_folder):
                os.makedirs(azure_folder)
            ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
            CONFIG.load(os.path.join(azure_folder, 'az.json'))
            SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

            self.app.initialize(Configuration())

            if '--progress' in args:
                args.remove('--progress')
                thread = ExecuteThread(self.app.execute, args)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                self.curr_thread = thread

                thread = ProgressViewThread(progress_view, self)
                thread.daemon = True
                thread.start()
                self.threads.append(thread)
                result = None

            else:
                result = self.app.execute(args)

            self.last_exit = 0
            if result and result.result is not None:
                from azure.cli.core._output import OutputProducer
                if self.output:
                    self.output.write(result)
                    self.output.flush()
                else:
                    formatter = OutputProducer.get_formatter(
                        self.app.configuration.output_format)
                    OutputProducer(formatter=formatter, file=self.output).out(result)
                    self.last = result

        except Exception as ex:  # pylint: disable=broad-except
            self.last_exit = handle_exception(ex)
        except SystemExit as ex:
            self.last_exit = int(ex.code)
예제 #19
0
    def __init__(self, **kwargs):
        super(AzCli, self).__init__(**kwargs)

        from azure.cli.core.commands import register_cache_arguments
        from azure.cli.core.commands.arm import (
            register_ids_argument, register_global_subscription_argument)
        from azure.cli.core.cloud import get_active_cloud
        from azure.cli.core.commands.transform import register_global_transforms
        from azure.cli.core._session import ACCOUNT, CONFIG, SESSION, INDEX, VERSIONS
        from azure.cli.core.style import format_styled_text
        from azure.cli.core.util import handle_version_update
        from azure.cli.core.commands.query_examples import register_global_query_examples_argument

        from knack.util import ensure_dir

        self.data['headers'] = {}
        self.data['command'] = 'unknown'
        self.data['command_extension_name'] = None
        self.data['completer_active'] = ARGCOMPLETE_ENV_NAME in os.environ
        self.data['query_active'] = False

        azure_folder = self.config.config_dir
        ensure_dir(azure_folder)
        ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
        CONFIG.load(os.path.join(azure_folder, 'az.json'))
        SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)
        INDEX.load(os.path.join(azure_folder, 'commandIndex.json'))
        VERSIONS.load(os.path.join(azure_folder, 'versionCheck.json'))
        handle_version_update()

        self.cloud = get_active_cloud(self)
        logger.debug('Current cloud config:\n%s', str(self.cloud.name))
        self.local_context = AzCLILocalContext(self)
        register_global_transforms(self)
        register_global_subscription_argument(self)
        register_global_query_examples_argument(self)
        register_ids_argument(
            self)  # global subscription must be registered first!
        register_cache_arguments(self)

        self.progress_controller = None

        if self.enable_color:
            theme = self.config.get('core', 'theme', fallback='dark')
        else:
            theme = 'none'
        format_styled_text.theme = theme
예제 #20
0
def main(style=None):
    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = SHELL_CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    if style:
        given_style = style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style_obj = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        print("When in doubt, ask for 'help'")
        config.firsttime()

    ask_feedback = False
    if not config.has_feedback() and frequent_user:
        print("\n\nAny comments or concerns? You can use the \'feedback\' command!" +
              " We would greatly appreciate it.\n")
        ask_feedback = True

    shell_app = Shell(
        completer=AZCOMPLETER,
        lexer=AzLexer,
        history=FileHistory(
            os.path.join(shell_config_dir(), config.get_history())),
        app=APPLICATION,
        styles=style_obj,
        user_feedback=ask_feedback
    )
    shell_app.run()
예제 #21
0
def main(style=None):
    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = SHELL_CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    if style:
        given_style = style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style_obj = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        print("When in doubt, ask for 'help'")
        config.firsttime()

    ask_feedback = False
    if not config.has_feedback() and frequent_user:
        print(
            "\n\nAny comments or concerns? You can use the \'feedback\' command!"
            + " We would greatly appreciate it.\n")
        ask_feedback = True

    shell_app = Shell(completer=AZCOMPLETER,
                      lexer=AzLexer,
                      history=FileHistory(
                          os.path.join(shell_config_dir(),
                                       config.get_history())),
                      app=APPLICATION,
                      styles=style_obj,
                      user_feedback=ask_feedback)
    shell_app.run()
예제 #22
0
def get_azure_cli_auth_token(resource):
    from adal import AuthenticationContext
    import os

    try:
        # this makes it cleaner, but in case azure cli is not present on virtual env,
        # but cli exists on computer, we can try and manually get the token from the cache
        from azure.cli.core._profile import Profile
        from azure.cli.core._session import ACCOUNT
        from azure.cli.core._environment import get_config_dir

        azure_folder = get_config_dir()
        ACCOUNT.load(os.path.join(azure_folder, "azureProfile.json"))
        profile = Profile(storage=ACCOUNT)
        token_data = profile.get_raw_token()[0][2]

        client_id = token_data["_clientId"]
        refresh_token = token_data["refreshToken"]

        logger.info(f"Found existing AZ CLI profile for {token_data[0]['userId']}")

    except ModuleNotFoundError:
        try:
            import os
            import json

            folder = os.getenv("AZURE_CONFIG_DIR", None) or os.path.expanduser(os.path.join("~", ".azure"))
            token_path = os.path.join(folder, "accessTokens.json")
            with open(token_path) as f:
                data = json.load(f)

            client_id = data[0]["_clientId"]
            refresh_token = data[0]["refreshToken"]

            logger.info(f"Found existing AZ CLI profile for {data[0]['userId']}")
        except Exception:
            return None

    return AuthenticationContext(f"https://login.microsoftonline.com/common").acquire_token_with_refresh_token(
        refresh_token, client_id, f"https://{resource}.kusto.windows.net"
    )["accessToken"]
예제 #23
0
def main(args):
    os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__

    parser = argparse.ArgumentParser(prog='az-shell')
    parser.add_argument('--style',
                        dest='style',
                        help='the colors of the shell',
                        choices=get_options())
    args = parser.parse_args(args)

    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    config = SHELL_CONFIGURATION
    shell_config_dir = azclishell.configuration.get_config_dir

    if args.style:
        given_style = args.style
        config.set_style(given_style)
    else:
        given_style = config.get_style()

    style = style_factory(given_style)

    if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]:
        print("When in doubt, ask for 'help'")
        config.firsttime()

    shell_app = Shell(completer=AZCOMPLETER,
                      lexer=AzLexer,
                      history=FileHistory(
                          os.path.join(shell_config_dir(),
                                       config.get_history())),
                      app=APPLICATION,
                      styles=style)
    shell_app.run()
예제 #24
0
def get_cli_profile():
    """Return a CLI profile class.

    .. versionadded:: 1.1.6

    :return: A CLI Profile
    :rtype: azure.cli.core._profile.Profile
    :raises: ImportError if azure-cli-core package is not available
    """

    try:
        from azure.cli.core._profile import Profile
        from azure.cli.core._session import ACCOUNT
        from azure.cli.core._environment import get_config_dir
    except ImportError:
        raise ImportError("You need to install 'azure-cli-core' to load CLI credentials")


    azure_folder = get_config_dir()
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    return Profile(ACCOUNT)
예제 #25
0
def get_cli_profile():
    """Return a CLI profile class.

    .. versionadded:: 1.1.6

    :return: A CLI Profile
    :rtype: azure.cli.core._profile.Profile
    :raises: ImportError if azure-cli-core package is not available
    """

    try:
        from azure.cli.core._profile import Profile
        from azure.cli.core._session import ACCOUNT
        from azure.cli.core._environment import get_config_dir
    except ImportError:
        raise ImportError(
            "You need to install 'azure-cli-core' to load CLI credentials")

    azure_folder = get_config_dir()
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    return Profile(storage=ACCOUNT)
예제 #26
0
def main(args, output=sys.stdout, logging_stream=None):
    configure_logging(args, logging_stream)

    logger = get_az_logger(__name__)
    logger.debug('Command arguments %s', args)

    if args and (args[0] == '--version' or args[0] == '-v'):
        show_version_info_exit(output)

    azure_folder = get_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    CONFIG.load(os.path.join(azure_folder, 'az.json'))
    SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

    APPLICATION.initialize(Configuration())

    try:
        cmd_result = APPLICATION.execute(args)

        # Commands can return a dictionary/list of results
        # If they do, we print the results.
        if cmd_result and cmd_result.result is not None:
            from azure.cli.core._output import OutputProducer
            formatter = OutputProducer.get_formatter(
                APPLICATION.configuration.output_format)
            OutputProducer(formatter=formatter, file=output).out(cmd_result)

    except Exception as ex:  # pylint: disable=broad-except

        # TODO: include additional details of the exception in telemetry
        telemetry.set_exception(
            ex, 'outer-exception',
            'Unexpected exception caught during application execution.')
        telemetry.set_failure()

        error_code = handle_exception(ex)
        return error_code
예제 #27
0
    def run(self):
        """ runs the CLI """
        telemetry.start()
        self.cli.buffers['symbols'].reset(
            initial_document=Document(u'%s' %shell_help)
        )
        while True:
            try:
                document = self.cli.run(reset_current_buffer=True)
                text = document.text
                cmd = text
                outside = False
                if text.split() and text.split()[0] == 'az':
                    cmd = ' '.join(text.split()[1:])
                if self.default_command:
                    cmd = self.default_command + " " + cmd
                # if self.default_params:
                #     for param in self.default_params:
                #         cmd += ' ' + param

            except AttributeError:  # when the user pressed Control Q
                break
            else:
                if text.strip() == "quit" or text.strip() == "exit":
                    break
                elif text.strip() == "clear":  # clears the history, but only when you restart
                    outside = True
                    cmd = 'echo -n "" >' +\
                        os.path.join(
                            SHELL_CONFIGURATION.get_config_dir(),
                            SHELL_CONFIGURATION.get_history())
                elif text.strip() == "help":
                    print(help_doc.dump(shell_help))
                if text:
                    if text[0] == SELECT_SYMBOL['outside']:
                        cmd = text[1:]
                        outside = True
                    # elif text.split()[0] == "az":  # dumps the extra az
                    #     cmd = " ".join(text.split()[1:])
                    elif text[0] == SELECT_SYMBOL['exit_code']:
                        print(self.last_exit)
                        self.set_prompt()
                        continue
                    elif SELECT_SYMBOL['query'] in text:  # query previous output
                        if self.last and self.last.result:
                            if hasattr(self.last.result, '__dict__'):
                                input_dict = dict(self.last.result)
                            else:
                                input_dict = self.last.result
                            try:
                                result = jmespath.search(
                                    text.partition(SELECT_SYMBOL['query'])[2], input_dict)
                                if isinstance(result, str):
                                    print(result)
                                else:
                                    print(json.dumps(result, sort_keys=True, indent=2))
                            except jmespath.exceptions.ParseError:
                                print("Invalid Query")

                        self.set_prompt()
                        continue
                    elif "|" in text or ">" in text:  # anything I don't parse, send off
                        outside = True
                        cmd = "az " + cmd
                    elif SELECT_SYMBOL['example'] in text:
                        global NOTIFICATIONS
                        cmd = self.handle_example(text)
                if SELECT_SYMBOL['default'] in text:
                    default = text.partition(SELECT_SYMBOL['default'])[2].split()
                    if default[0].startswith('-'):
                        value = self.handle_default_param(default)
                    else:
                        value = self.handle_default_command(default)
                    print("defaulting: " + value)
                    self.set_prompt()
                    continue
                if SELECT_SYMBOL['undefault'] in text:
                    value = text.partition(SELECT_SYMBOL['undefault'])[2].split()
                    if len(value) == 0:
                        self.default_command = ""
                        set_default_command("", add=False)
                        # self.default_params = []
                        print('undefaulting all')
                    elif len(value) == 1 and value[0] == self.default_command:
                        self.default_command = ""
                        set_default_command("", add=False)
                        print('undefaulting: ' + value[0])
                    # elif len(value) == 2 and ' '.join(value[:2]) in self.default_params:
                    #     self.default_params.remove(' '.join(value[:2]))
                    #     print('undefaulting: ' + ' '.join(value[:2]))

                    self.set_prompt()
                    continue

                if not text: # not input
                    self.set_prompt()
                    continue

                self.history.append(cmd)
                self.set_prompt()
                if outside:
                    subprocess.Popen(cmd, shell=True).communicate()
                else:
                    try:
                        args = [str(command) for command in cmd.split()]
                        azlogging.configure_logging(args)

                        azure_folder = get_config_dir()
                        if not os.path.exists(azure_folder):
                            os.makedirs(azure_folder)
                        ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
                        CONFIG.load(os.path.join(azure_folder, 'az.json'))
                        SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600)

                        config = Configuration(args)
                        self.app.initialize(config)

                        result = self.app.execute(args)
                        if result and result.result is not None:
                            from azure.cli.core._output import OutputProducer, format_json
                            if self.output:
                                self.output.out(result)
                            else:
                                formatter = OutputProducer.get_formatter(
                                    self.app.configuration.output_format)
                                OutputProducer(formatter=formatter, file=self.input).out(result)
                                self.last = result
                                self.last_exit = 0
                    except Exception as ex:  # pylint: disable=broad-except
                        self.last_exit = handle_exception(ex)
                    except SystemExit as ex:
                        self.last_exit = ex.code
                    if self.last_exit != 0:
                        telemetry.set_failure()
                    else:
                        telemetry.set_success()

        print('Have a lovely day!!')
        telemetry.conclude()
예제 #28
0
def _load_profile():
    azure_folder = cli_config_dir()
    if not os.path.exists(azure_folder):
        os.makedirs(azure_folder)

    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))