Ejemplo n.º 1
0
    def select_sub(self, line):
        from azure.cli.core._profile import Profile
        try:
            from azure.cli.core.util import CLIError
        except ImportError:
            from azure.cli.core._util import CLIError
        self._redirect_logging('az.azure.cli.core._profile')
        p = argparse.ArgumentParser()
        p.add_argument('subscription')
        parsed_args = p.parse_args(shlex.split(line))

        # if user is already logged in, get their subscriptions
        profile = Profile()
        subs = profile.load_cached_subscriptions()
        if not subs:
            # user not logged in--prompt them
            profile.find_subscriptions_on_login(True, None, None, None, None)

        try:
            profile.set_active_subscription(parsed_args.subscription)
            print('Active subscription set to {}'.format(
                profile.get_subscription()['name']))
        except CLIError as exc:
            print(exc)
            print('Active subscription remains {}'.format(
                profile.get_subscription()['name']))
Ejemplo n.º 2
0
    def test_get_expanded_subscription_info_for_logged_in_service_principal(self,
                                                                            mock_auth_context):
        mock_auth_context.acquire_token_with_client_credentials.return_value = self.token_entry1
        mock_arm_client = mock.MagicMock()
        mock_arm_client.subscriptions.list.return_value = [self.subscription1]
        finder = SubscriptionFinder(lambda _, _2: mock_auth_context,
                                    None,
                                    lambda _: mock_arm_client)

        storage_mock = {'subscriptions': []}
        profile = Profile(storage_mock, use_global_creds_cache=False)
        profile._management_resource_uri = 'https://management.core.windows.net/'
        profile.find_subscriptions_on_login(False,
                                            '1234',
                                            'my-secret',
                                            True,
                                            self.tenant_id,
                                            False,
                                            finder)
        # action
        extended_info = profile.get_expanded_subscription_info()
        # assert
        self.assertEqual(self.id1.split('/')[-1], extended_info['subscriptionId'])
        self.assertEqual(self.display_name1, extended_info['subscriptionName'])
        self.assertEqual('1234', extended_info['client'])
        self.assertEqual('https://login.microsoftonline.com',
                         extended_info['endpoints'].active_directory)
Ejemplo n.º 3
0
    def test_get_expanded_subscription_info_for_logged_in_service_principal(self,
                                                                            mock_auth_context):
        mock_auth_context.acquire_token_with_client_credentials.return_value = self.token_entry1
        mock_arm_client = mock.MagicMock()
        mock_arm_client.subscriptions.list.return_value = [self.subscription1]
        finder = SubscriptionFinder(lambda _, _2: mock_auth_context,
                                    None,
                                    lambda _: mock_arm_client)

        storage_mock = {'subscriptions': []}
        profile = Profile(storage_mock, use_global_creds_cache=False)
        profile._management_resource_uri = 'https://management.core.windows.net/'
        profile.find_subscriptions_on_login(False,
                                            '1234',
                                            'my-secret',
                                            True,
                                            self.tenant_id,
                                            False,
                                            finder)
        # action
        extended_info = profile.get_expanded_subscription_info()
        # assert
        self.assertEqual(self.id1.split('/')[-1], extended_info['subscriptionId'])
        self.assertEqual(self.display_name1, extended_info['subscriptionName'])
        self.assertEqual('1234', extended_info['client'])
        self.assertEqual('https://login.microsoftonline.com',
                         extended_info['endpoints'].active_directory)
Ejemplo n.º 4
0
    def list_subs(self, line):
        from azure.cli.core._profile import Profile
        try:
            from azure.cli.core.util import CLIError
        except ImportError:
            from azure.cli.core._util import CLIError
        self._redirect_logging('az.azure.cli.core._profile')

        # load cached credentials in Profile() object
        profile = Profile()
        try:
            # if user is logged in, get their current subscription
            profile.get_subscription()
        except CLIError:
            # otherwise interactively prompy user to log in
            profile.find_subscriptions_on_login(True, None, None, None, None)

        # list all subscriptions
        subs = profile.load_cached_subscriptions()
        if not subs:
            print('No subscriptions available.')
            print('Please run `az login` from the console then try again')
            return
        print("Available subscriptions:\n  {}".format('\n  '.join(
            [sub['name'] for sub in subs])))
def login(username, password, tenant):
    """Log in to access Azure subscriptions"""
    interactive = False
    profile = Profile()
    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive, username, password, True, tenant)
    except AdalError as err:
        # try polish unfriendly server errors
        msg = str(err)
        suggestion = "For cross-check, try 'az login' to authenticate through browser."
        if ('ID3242:' in msg) or ('Server returned an unknown AccountType'
                                  in msg):
            raise CLIError("The user name might be invalid. " + suggestion)
        if 'Server returned error in RSTR - ErrorCode' in msg:
            raise CLIError(
                "Logging in through command line is not supported. " +
                suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError(
            'Please ensure you have network connection. Error detail: ' +
            str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions
Ejemplo n.º 6
0
def login(username=None, password=None, service_principal=None, tenant=None):
    '''Log in to access Azure subscriptions'''
    interactive = False

    if username:
        if not password:
            import getpass
            password = getpass.getpass('Password: '******'az login' to authenticate through browser"
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType'
                                      in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError(
                    "Logging in through command line is not supported. " +
                    suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError(
            'Please ensure you have network connection. Error detail: ' +
            str(err))
    return list(subscriptions)
Ejemplo n.º 7
0
def login(username=None, password=None, service_principal=None, tenant=None):
    '''Log in to access Azure subscriptions'''
    interactive = False

    if username:
        if not password:
            import getpass
            password = getpass.getpass('Password: '******'az login' to authenticate through browser"
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType' in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError("Logging in through command line is not supported. " + suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError('Please ensure you have network connection. Error detail: ' + str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions
Ejemplo n.º 8
0
def login(username=None, password=None, service_principal=None, tenant=None,
          allow_no_subscriptions=False, msi=False, msi_port=DefaultStr(50342)):
    """Log in to access Azure subscriptions"""
    import os
    import re
    from adal.adal_error import AdalError
    import requests

    # quick argument usage check
    if (any([username, password, service_principal, tenant, allow_no_subscriptions]) and
            any([msi, not getattr(msi_port, 'is_default', None)])):
        raise CLIError("usage error: '--msi/--msi-port' are not applicable with other arguments")

    interactive = False

    profile = Profile()

    if in_cloud_console():
        console_tokens = os.environ.get('AZURE_CONSOLE_TOKENS', None)
        if console_tokens:
            return profile.find_subscriptions_in_cloud_console(re.split(';|,', console_tokens))
        logger.warning(_CLOUD_CONSOLE_WARNING_TEMPLATE, 'login')
        return

    if msi:
        return profile.find_subscriptions_in_vm_with_msi(msi_port)

    if username:
        if not password:
            try:
                password = prompt_pass('Password: '******'Please specify both username and password in non-interactive mode.')
    else:
        interactive = True

    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive,
            username,
            password,
            service_principal,
            tenant,
            allow_no_subscriptions=allow_no_subscriptions)
    except AdalError as err:
        # try polish unfriendly server errors
        if username:
            msg = str(err)
            suggestion = "For cross-check, try 'az login' to authenticate through browser."
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType' in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError("Logging in through command line is not supported. " + suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError('Please ensure you have network connection. Error detail: ' + str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions
Ejemplo n.º 9
0
def login(username=None, password=None, service_principal=None, tenant=None,
          allow_no_subscriptions=False, msi=False, msi_port=DefaultStr(50342)):
    """Log in to access Azure subscriptions"""
    import os
    import re
    from adal.adal_error import AdalError
    import requests

    # quick argument usage check
    if (any([username, password, service_principal, tenant, allow_no_subscriptions]) and
            any([msi, not getattr(msi_port, 'is_default', None)])):
        raise CLIError("usage error: '--msi/--msi-port' are not applicable with other arguments")

    interactive = False

    profile = Profile()

    if _in_cloud_console():
        console_tokens = os.environ.get('AZURE_CONSOLE_TOKENS', None)
        if console_tokens:
            return profile.find_subscriptions_in_cloud_console(re.split(';|,', console_tokens))
        else:
            raise CLIError(_CLOUD_CONSOLE_ERR_TEMPLATE.format('login'))

    if msi:
        return profile.find_subscriptions_in_vm_with_msi(msi_port)

    if username:
        if not password:
            try:
                password = prompt_pass('Password: '******'Please specify both username and password in non-interactive mode.')
    else:
        interactive = True

    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive,
            username,
            password,
            service_principal,
            tenant,
            allow_no_subscriptions=allow_no_subscriptions)
    except AdalError as err:
        # try polish unfriendly server errors
        if username:
            msg = str(err)
            suggestion = "For cross-check, try 'az login' to authenticate through browser."
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType' in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError("Logging in through command line is not supported. " + suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError('Please ensure you have network connection. Error detail: ' + str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions
Ejemplo n.º 10
0
    def test_create_account_without_subscriptions(self, mock_auth_context):
        mock_auth_context.acquire_token_with_client_credentials.return_value = self.token_entry1
        mock_arm_client = mock.MagicMock()
        mock_arm_client.subscriptions.list.return_value = []
        finder = SubscriptionFinder(lambda _, _2: mock_auth_context,
                                    None,
                                    lambda _: mock_arm_client)

        storage_mock = {'subscriptions': []}
        profile = Profile(storage_mock, use_global_creds_cache=False)
        profile._management_resource_uri = 'https://management.core.windows.net/'

        # action
        result = profile.find_subscriptions_on_login(False,
                                                     '1234',
                                                     'my-secret',
                                                     True,
                                                     self.tenant_id,
                                                     allow_no_subscriptions=True,
                                                     subscription_finder=finder)

        # assert
        self.assertTrue(1, len(result))
        self.assertEqual(result[0]['id'], self.tenant_id)
        self.assertEqual(result[0]['state'], 'Enabled')
        self.assertEqual(result[0]['tenantId'], self.tenant_id)
        self.assertEqual(result[0]['name'], 'N/A(tenant level account)')
Ejemplo n.º 11
0
    def test_create_account_without_subscriptions_thru_common_tenant(self, mock_auth_context):
        mock_auth_context.acquire_token.return_value = self.token_entry1
        mock_auth_context.acquire_token_with_username_password.return_value = self.token_entry1
        tenant_object = mock.MagicMock()
        tenant_object.id = "foo-bar"
        tenant_object.tenant_id = self.tenant_id
        mock_arm_client = mock.MagicMock()
        mock_arm_client.subscriptions.list.return_value = []
        mock_arm_client.tenants.list.return_value = (x for x in [tenant_object])

        finder = SubscriptionFinder(lambda _, _2: mock_auth_context,
                                    None,
                                    lambda _: mock_arm_client)

        storage_mock = {'subscriptions': []}
        profile = Profile(storage_mock, use_global_creds_cache=False)
        profile._management_resource_uri = 'https://management.core.windows.net/'

        # action
        result = profile.find_subscriptions_on_login(False,
                                                     '1234',
                                                     'my-secret',
                                                     False,
                                                     None,
                                                     allow_no_subscriptions=True,
                                                     subscription_finder=finder)

        # assert
        self.assertEqual(1, len(result))
        self.assertEqual(result[0]['id'], self.tenant_id)
        self.assertEqual(result[0]['state'], 'Enabled')
        self.assertEqual(result[0]['tenantId'], self.tenant_id)
        self.assertEqual(result[0]['name'], 'N/A(tenant level account)')
Ejemplo n.º 12
0
def login(username=None, password=None, service_principal=None, tenant=None):
    '''Log in to access Azure subscriptions'''
    interactive = False

    if username:
        if not password:
            import getpass
            password = getpass.getpass('Password: '******'az login' to authenticate through browser"
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType' in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError("Logging in through command line is not supported. " + suggestion)
        raise CLIError(err)
    return list(subscriptions)
Ejemplo n.º 13
0
def _config_env_public_azure(cli_ctx, _):
    from adal.adal_error import AdalError
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    from azure.cli.core._profile import Profile
    from azure.cli.core.profiles import ResourceType
    # Determine if user logged in

    try:
        list(
            get_mgmt_service_client(
                cli_ctx,
                ResourceType.MGMT_RESOURCE_RESOURCES).resources.list())
    except CLIError:
        # Not logged in
        login_successful = False
        while not login_successful:
            method_index = prompt_choice_list(MSG_PROMPT_LOGIN,
                                              LOGIN_METHOD_LIST)
            answers['login_index'] = method_index
            answers['login_options'] = str(LOGIN_METHOD_LIST)
            profile = Profile(cli_ctx=cli_ctx)
            interactive = False
            username = None
            password = None
            service_principal = None
            tenant = None
            if method_index == 0:  # device auth
                interactive = True
            elif method_index == 1:  # username and password
                username = prompt('Username: '******'Password: '******'Service principal: ')
                tenant = prompt('Tenant: ')
                password = prompt_pass(msg='Client secret: ')
            elif method_index == 3:  # skip
                return
            try:
                profile.find_subscriptions_on_login(interactive, username,
                                                    password,
                                                    service_principal, tenant)
                login_successful = True
                logger.warning('Login successful!')
            except AdalError as err:
                logger.error('Login error!')
                logger.error(err)
Ejemplo n.º 14
0
def login(cmd, username=None, password=None, service_principal=None, tenant=None, allow_no_subscriptions=False,
          identity=False, identity_port=None):
    """Log in to access Azure subscriptions"""
    from adal.adal_error import AdalError
    import requests

    # quick argument usage check
    if (any([password, service_principal, tenant, allow_no_subscriptions]) and identity):
        raise CLIError("usage error: '--identity' is not applicable with other arguments")

    if identity_port:
        logger.warning("'--identity-port' is no longer required to login using managed identity."
                       " This flag will be removed in a future release of CLI.")

    interactive = False

    profile = Profile(cli_ctx=cmd.cli_ctx, async_persist=False)

    if identity:
        if in_cloud_console():
            return profile.find_subscriptions_in_cloud_console()
        return profile.find_subscriptions_in_vm_with_msi(username)
    elif in_cloud_console():  # tell users they might not need login
        logger.warning(_CLOUD_CONSOLE_LOGIN_WARNING)

    if username:
        if not password:
            try:
                password = prompt_pass('Password: '******'Please specify both username and password in non-interactive mode.')
    else:
        interactive = True

    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive,
            username,
            password,
            service_principal,
            tenant,
            allow_no_subscriptions=allow_no_subscriptions)
    except AdalError as err:
        # try polish unfriendly server errors
        if username:
            msg = str(err)
            suggestion = "For cross-check, try 'az login' to authenticate through browser."
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType' in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError("Logging in through command line is not supported. " + suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError('Please ensure you have network connection. Error detail: ' + str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions
Ejemplo n.º 15
0
def _config_env_public_azure(_):
    from adal.adal_error import AdalError
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    from azure.mgmt.resource import ResourceManagementClient
    from azure.cli.core._profile import Profile
    # Determine if user logged in
    try:
        list(get_mgmt_service_client(ResourceManagementClient).resources.list())
    except CLIError:
        # Not logged in
        login_successful = False
        while not login_successful:
            method_index = prompt_choice_list(MSG_PROMPT_LOGIN, LOGIN_METHOD_LIST)
            answers['login_index'] = method_index
            answers['login_options'] = str(LOGIN_METHOD_LIST)
            profile = Profile()
            interactive = False
            username = None
            password = None
            service_principal = None
            tenant = None
            if method_index == 0:  # device auth
                interactive = True
            elif method_index == 1:  # username and password
                username = prompt('Username: '******'Password: '******'Service principal: ')
                tenant = prompt('Tenant: ')
                password = prompt_pass(msg='Client secret: ')
            elif method_index == 3:  # skip
                return
            try:
                profile.find_subscriptions_on_login(
                    interactive,
                    username,
                    password,
                    service_principal,
                    tenant)
                login_successful = True
                logger.warning('Login successful!')
            except AdalError as err:
                logger.error('Login error!')
                logger.error(err)
Ejemplo n.º 16
0
def login(cmd, username=None, password=None, service_principal=None, tenant=None, allow_no_subscriptions=False,
          identity=False, use_device_code=False):
    """Log in to access Azure subscriptions"""
    from adal.adal_error import AdalError
    import requests

    # quick argument usage check
    if any([password, service_principal, tenant, allow_no_subscriptions]) and identity:
        raise CLIError("usage error: '--identity' is not applicable with other arguments")
    if any([password, service_principal, username, identity]) and use_device_code:
        raise CLIError("usage error: '--use-device-code' is not applicable with other arguments")

    interactive = False

    profile = Profile(cli_ctx=cmd.cli_ctx, async_persist=False)

    if identity:
        if in_cloud_console():
            return profile.find_subscriptions_in_cloud_console()
        return profile.find_subscriptions_in_vm_with_msi(username)
    elif in_cloud_console():  # tell users they might not need login
        logger.warning(_CLOUD_CONSOLE_LOGIN_WARNING)

    if username:
        if not password:
            try:
                password = prompt_pass('Password: '******'Please specify both username and password in non-interactive mode.')
    else:
        interactive = True

    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive,
            username,
            password,
            service_principal,
            tenant,
            use_device_code=use_device_code,
            allow_no_subscriptions=allow_no_subscriptions)
    except AdalError as err:
        # try polish unfriendly server errors
        if username:
            msg = str(err)
            suggestion = "For cross-check, try 'az login' to authenticate through browser."
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType' in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError("Logging in through command line is not supported. " + suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError('Please ensure you have network connection. Error detail: ' + str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions
 def list_subs(self, line):
     from azure.cli.core._profile import Profile
     try:
         from azure.cli.core.util import CLIError
     except ImportError:
         from azure.cli.core._util import CLIError
     self._redirect_logging('az.azure.cli.core._profile')
     profile = Profile()
     try:
         profile.get_subscription()
     except CLIError:
         profile.find_subscriptions_on_login(True, None, None, None, None)
     subs = profile.load_cached_subscriptions()
     if not subs:
         print('No subscriptions available.')
         print('Please run `az login` from the console then try again')
         return
     print("Available subscriptions:\n  {}".format('\n  '.join(
         [sub['name'] for sub in subs])))
Ejemplo n.º 18
0
def login(username=None, password=None, service_principal=None, tenant=None,
          allow_no_subscriptions=False):
    """Log in to access Azure subscriptions"""
    import os
    import re
    from adal.adal_error import AdalError
    import requests
    interactive = False

    profile = Profile()

    if username:
        if not password:
            # in a VM with managed service identity?
            result = profile.init_if_in_msi_env(username)
            if result:
                return result
            try:
                password = prompt_pass('Password: '******'Please specify both username and password in non-interactive mode.')
    else:
        # in a cloud console?
        console_tokens = os.environ.get('AZURE_CONSOLE_TOKENS', None)
        if console_tokens:
            return profile.find_subscriptions_in_cloud_console(re.split(';|,', console_tokens))

        interactive = True

    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive,
            username,
            password,
            service_principal,
            tenant,
            allow_no_subscriptions=allow_no_subscriptions)
    except AdalError as err:
        # try polish unfriendly server errors
        if username:
            msg = str(err)
            suggestion = "For cross-check, try 'az login' to authenticate through browser."
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType' in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError("Logging in through command line is not supported. " + suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError('Please ensure you have network connection. Error detail: ' + str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions
Ejemplo n.º 19
0
    def test_create_account_without_subscriptions_without_tenant(self, mock_auth_context):
        finder = mock.MagicMock()
        finder.find_through_interactive_flow.return_value = []
        storage_mock = {'subscriptions': []}
        profile = Profile(storage_mock, use_global_creds_cache=False)

        # action
        result = profile.find_subscriptions_on_login(True,
                                                     '1234',
                                                     'my-secret',
                                                     False,
                                                     None,
                                                     allow_no_subscriptions=True,
                                                     subscription_finder=finder)

        # assert
        self.assertTrue(0 == len(result))
Ejemplo n.º 20
0
    def test_create_account_without_subscriptions_without_tenant(self, mock_auth_context):
        finder = mock.MagicMock()
        finder.find_through_interactive_flow.return_value = []
        storage_mock = {'subscriptions': []}
        profile = Profile(storage_mock, use_global_creds_cache=False)

        # action
        result = profile.find_subscriptions_on_login(True,
                                                     '1234',
                                                     'my-secret',
                                                     False,
                                                     None,
                                                     allow_no_subscriptions=True,
                                                     subscription_finder=finder)

        # assert
        self.assertTrue(0 == len(result))
Ejemplo n.º 21
0
def login(username=None, password=None, service_principal=None, tenant=None):
    """Log in to access Azure subscriptions"""
    from adal.adal_error import AdalError
    import requests
    interactive = False

    if username:
        if not password:
            try:
                password = prompt_pass('Password: '******'Please specify both username and password in non-interactive mode.'
                )
    else:
        interactive = True

    profile = Profile()
    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive, username, password, service_principal, tenant)
    except AdalError as err:
        # try polish unfriendly server errors
        if username:
            msg = str(err)
            suggestion = "For cross-check, try 'az login' to authenticate through browser."
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType'
                                      in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError(
                    "Logging in through command line is not supported. " +
                    suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError(
            'Please ensure you have network connection. Error detail: ' +
            str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions
Ejemplo n.º 22
0
def login(username=None, password=None, service_principal=None, tenant=None):
    """Log in to access Azure subscriptions"""
    interactive = False

    if username:
        if not password:
            try:
                password = prompt_pass('Password: '******'Please specify both username and password in non-interactive mode.')
    else:
        interactive = True

    profile = Profile()
    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive,
            username,
            password,
            service_principal,
            tenant)
    except AdalError as err:
        # try polish unfriendly server errors
        if username:
            msg = str(err)
            suggestion = "For cross-check, try 'az login' to authenticate through browser."
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType' in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError("Logging in through command line is not supported. " + suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError('Please ensure you have network connection. Error detail: ' + str(err))
    # use deepcopy as we don't want to persist these changes to file.
    all_subscriptions = deepcopy(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions
Ejemplo n.º 23
0
def login(cmd,
          username=None,
          password=None,
          service_principal=None,
          tenant=None,
          allow_no_subscriptions=False,
          identity=False,
          use_device_code=False,
          use_cert_sn_issuer=None):
    """Log in to access Azure subscriptions"""
    from adal.adal_error import AdalError
    import requests

    # quick argument usage check
    if any([password, service_principal, tenant]) and identity:
        raise CLIError(
            "usage error: '--identity' is not applicable with other arguments")
    if any([password, service_principal, username, identity
            ]) and use_device_code:
        raise CLIError(
            "usage error: '--use-device-code' is not applicable with other arguments"
        )
    if use_cert_sn_issuer and not service_principal:
        raise CLIError(
            "usage error: '--use-sn-issuer' is only applicable with a service principal"
        )
    if service_principal and not username:
        raise CLIError(
            'usage error: --service-principal --username NAME --password SECRET --tenant TENANT'
        )

    interactive = False

    profile = Profile(cli_ctx=cmd.cli_ctx, async_persist=False)

    if identity:
        if in_cloud_console():
            return profile.find_subscriptions_in_cloud_console()
        return profile.find_subscriptions_in_vm_with_msi(
            username, allow_no_subscriptions)
    if in_cloud_console():  # tell users they might not need login
        logger.warning(_CLOUD_CONSOLE_LOGIN_WARNING)

    if username:
        if not password:
            try:
                password = prompt_pass('Password: '******'Please specify both username and password in non-interactive mode.'
                )
    else:
        interactive = True

    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive,
            username,
            password,
            service_principal,
            tenant,
            use_device_code=use_device_code,
            allow_no_subscriptions=allow_no_subscriptions,
            use_cert_sn_issuer=use_cert_sn_issuer)
    except AdalError as err:
        # try polish unfriendly server errors
        if username:
            msg = str(err)
            suggestion = "For cross-check, try 'az login' to authenticate through browser."
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType'
                                      in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError(
                    "Logging in through command line is not supported. " +
                    suggestion)
            if 'wstrust' in msg:
                raise CLIError(
                    "Authentication failed due to error of '" + msg + "' "
                    "This typically happens when attempting a Microsoft account, which requires "
                    "interactive login. Please invoke 'az login' to cross check. "
                    # pylint: disable=line-too-long
                    "More details are available at https://github.com/AzureAD/microsoft-authentication-library-for-python/wiki/Username-Password-Authentication"
                )
        raise CLIError(err)
    except requests.exceptions.SSLError as err:
        from azure.cli.core.util import SSLERROR_TEMPLATE
        raise CLIError(SSLERROR_TEMPLATE.format(str(err)))
    except requests.exceptions.ConnectionError as err:
        raise CLIError(
            'Please ensure you have network connection. Error detail: ' +
            str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions
Ejemplo n.º 24
0
def login(cmd, username=None, password=None, service_principal=None, tenant=None, allow_no_subscriptions=False,
          identity=False, identity_port=None,
          msi=False, msi_port=None):  # will remove msi_xxx in a future release
    """Log in to access Azure subscriptions"""
    import os
    import re
    from adal.adal_error import AdalError
    import requests

    # quick argument usage check
    if (any([password, service_principal, tenant, allow_no_subscriptions]) and
            any([identity, msi])):
        raise CLIError("usage error: '--identity/--identity-port' are not applicable with other arguments")

    interactive = False

    profile = Profile(cli_ctx=cmd.cli_ctx, async_persist=False)

    # if identity or msi:
    #     if in_cloud_console():
    #         return profile.find_subscriptions_in_cloud_console()
    #     return profile.find_subscriptions_in_vm_with_msi(identity_port or msi_port or 50342, username)
    # elif in_cloud_console():  # tell users they might not need login
    #     logger.warning(_CLOUD_CONSOLE_LOGIN_WARNING)

    if in_cloud_console():
        console_tokens = os.environ.get('AZURE_CONSOLE_TOKENS', None)
        if console_tokens:
            return profile.find_subscriptions_in_cloud_console_thru_raw_token(re.split(';|,', console_tokens))
        logger.warning(_CLOUD_CONSOLE_WARNING_TEMPLATE, 'login')
        return

    if identity or msi:
        return profile.find_subscriptions_in_vm_with_msi(identity_port or msi_port or 50342, username)

    if username:
        if not password:
            try:
                password = prompt_pass('Password: '******'Please specify both username and password in non-interactive mode.')
    else:
        interactive = True

    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive,
            username,
            password,
            service_principal,
            tenant,
            allow_no_subscriptions=allow_no_subscriptions)
    except AdalError as err:
        # try polish unfriendly server errors
        if username:
            msg = str(err)
            suggestion = "For cross-check, try 'az login' to authenticate through browser."
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType' in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError("Logging in through command line is not supported. " + suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError('Please ensure you have network connection. Error detail: ' + str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions