Ejemplo n.º 1
0
def _get_ssh_path(ssh_command="ssh"):
    ssh_path = ssh_command

    if platform.system() == 'Windows':
        arch_data = platform.architecture()
        is_32bit = arch_data[0] == '32bit'
        sys_path = 'SysNative' if is_32bit else 'System32'
        system_root = os.environ['SystemRoot']
        system32_path = os.path.join(system_root, sys_path)
        ssh_path = os.path.join(system32_path, "openSSH",
                                (ssh_command + ".exe"))
        logger.debug("Platform architecture: %s", str(arch_data))
        logger.debug("System Root: %s", system_root)
        logger.debug("Attempting to run ssh from path %s", ssh_path)

        if not os.path.isfile(ssh_path):
            raise azclierror.UnclassifiedUserFault(
                "Could not find " + ssh_command + ".exe.",
                "https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse"
            )

    return ssh_path
Ejemplo n.º 2
0
def handle_exception(ex):  # pylint: disable=too-many-locals, too-many-statements, too-many-branches
    # For error code, follow guidelines at https://docs.python.org/2/library/sys.html#sys.exit,
    from jmespath.exceptions import JMESPathError
    from msrestazure.azure_exceptions import CloudError
    from msrest.exceptions import HttpOperationError, ValidationError, ClientRequestError
    from azure.common import AzureException
    from azure.core.exceptions import AzureError
    from requests.exceptions import SSLError, HTTPError
    import azure.cli.core.azclierror as azclierror
    import traceback

    logger.debug("azure.cli.core.util.handle_exception is called with an exception:")
    # Print the traceback and exception message
    logger.debug(traceback.format_exc())

    error_msg = getattr(ex, 'message', str(ex))
    exit_code = 1

    if isinstance(ex, azclierror.AzCLIError):
        az_error = ex

    elif isinstance(ex, JMESPathError):
        error_msg = "Invalid jmespath query supplied for `--query`: {}".format(error_msg)
        az_error = azclierror.InvalidArgumentValueError(error_msg)
        az_error.set_recommendation(QUERY_REFERENCE)

    elif isinstance(ex, SSLError):
        az_error = azclierror.AzureConnectionError(error_msg)
        az_error.set_recommendation(SSLERROR_TEMPLATE)

    elif isinstance(ex, CloudError):
        if extract_common_error_message(ex):
            error_msg = extract_common_error_message(ex)
        status_code = str(getattr(ex, 'status_code', 'Unknown Code'))
        AzCLIErrorType = get_error_type_by_status_code(status_code)
        az_error = AzCLIErrorType(error_msg)

    elif isinstance(ex, ValidationError):
        az_error = azclierror.ValidationError(error_msg)

    elif isinstance(ex, CLIError):
        # TODO: Fine-grained analysis here
        az_error = azclierror.UnclassifiedUserFault(error_msg)

    elif isinstance(ex, AzureError):
        if extract_common_error_message(ex):
            error_msg = extract_common_error_message(ex)
        AzCLIErrorType = get_error_type_by_azure_error(ex)
        az_error = AzCLIErrorType(error_msg)

    elif isinstance(ex, AzureException):
        if is_azure_connection_error(error_msg):
            az_error = azclierror.AzureConnectionError(error_msg)
        else:
            # TODO: Fine-grained analysis here for Unknown error
            az_error = azclierror.UnknownError(error_msg)

    elif isinstance(ex, ClientRequestError):
        if is_azure_connection_error(error_msg):
            az_error = azclierror.AzureConnectionError(error_msg)
        elif isinstance(ex.inner_exception, SSLError):
            # When msrest encounters SSLError, msrest wraps SSLError in ClientRequestError
            az_error = azclierror.AzureConnectionError(error_msg)
            az_error.set_recommendation(SSLERROR_TEMPLATE)
        else:
            az_error = azclierror.ClientRequestError(error_msg)

    elif isinstance(ex, HttpOperationError):
        message, _ = extract_http_operation_error(ex)
        if message:
            error_msg = message
        status_code = str(getattr(ex.response, 'status_code', 'Unknown Code'))
        AzCLIErrorType = get_error_type_by_status_code(status_code)
        az_error = AzCLIErrorType(error_msg)

    elif isinstance(ex, HTTPError):
        status_code = str(getattr(ex.response, 'status_code', 'Unknown Code'))
        AzCLIErrorType = get_error_type_by_status_code(status_code)
        az_error = AzCLIErrorType(error_msg)

    elif isinstance(ex, KeyboardInterrupt):
        error_msg = 'Keyboard interrupt is captured.'
        az_error = azclierror.ManualInterrupt(error_msg)

    else:
        error_msg = "The command failed with an unexpected error. Here is the traceback:"
        az_error = azclierror.CLIInternalError(error_msg)
        az_error.set_exception_trace(ex)
        az_error.set_recommendation("To open an issue, please run: 'az feedback'")

    if isinstance(az_error, azclierror.ResourceNotFoundError):
        exit_code = 3

    az_error.print_error()
    az_error.send_telemetry()

    return exit_code
Ejemplo n.º 3
0
def get_ssh_client_path(ssh_command="ssh", ssh_client_folder=None):
    if ssh_client_folder:
        ssh_path = os.path.join(ssh_client_folder, ssh_command)
        if platform.system() == 'Windows':
            ssh_path = ssh_path + '.exe'
        if os.path.isfile(ssh_path):
            logger.debug("Attempting to run %s from path %s", ssh_command,
                         ssh_path)
            return ssh_path
        logger.warning(
            "Could not find %s in provided --ssh-client-folder %s. "
            "Attempting to get pre-installed OpenSSH bits.", ssh_command,
            ssh_client_folder)

    ssh_path = ssh_command

    if platform.system() == 'Windows':
        # If OS architecture is 64bit and python architecture is 32bit,
        # look for System32 under SysNative folder.
        machine = platform.machine()
        os_architecture = None
        # python interpreter architecture
        platform_architecture = platform.architecture()[0]
        sys_path = None

        if machine.endswith('64'):
            os_architecture = '64bit'
        elif machine.endswith('86'):
            os_architecture = '32bit'
        elif machine == '':
            raise azclierror.BadRequestError(
                "Couldn't identify the OS architecture.")
        else:
            raise azclierror.BadRequestError(
                f"Unsuported OS architecture: {machine} is not currently supported"
            )

        if os_architecture == "64bit":
            sys_path = 'SysNative' if platform_architecture == '32bit' else 'System32'
        else:
            sys_path = 'System32'

        system_root = os.environ['SystemRoot']
        system32_path = os.path.join(system_root, sys_path)
        ssh_path = os.path.join(system32_path, "openSSH",
                                (ssh_command + ".exe"))
        logger.debug("Platform architecture: %s", platform_architecture)
        logger.debug("OS architecture: %s", os_architecture)
        logger.debug("System Root: %s", system_root)
        logger.debug("Attempting to run %s from path %s", ssh_command,
                     ssh_path)

        if not os.path.isfile(ssh_path):
            raise azclierror.UnclassifiedUserFault(
                "Could not find " + ssh_command + ".exe on path " + ssh_path +
                ". ", colorama.Fore.YELLOW +
                "Make sure OpenSSH is installed correctly: "
                "https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse . "
                "Or use --ssh-client-folder to provide folder path with ssh executables. "
                + colorama.Style.RESET_ALL)

    return ssh_path