예제 #1
0
def profile(ctx):
    """Manage user profiles

    """

    profiles = Profiles.load()
    click.echo(yaml.dump(profiles.data, default_flow_style=False))
예제 #2
0
def restore_session(ctx, vdc_required=False):
    if type(ctx.obj) is dict and 'client' in ctx.obj and ctx.obj[
            'client'] is not None:
        return
    profiles = Profiles.load()
    token = profiles.get('token')
    if token is None or len(token) == 0:
        raise Exception('Can\'t restore session, please login again.')
    if not profiles.get('verify'):
        if profiles.get('disable_warnings'):
            pass
        else:
            click.secho(
                'InsecureRequestWarning: '
                'Unverified HTTPS request is being made. '
                'Adding certificate verification is strongly '
                'advised.',
                fg='yellow',
                err=True)
        requests.packages.urllib3.disable_warnings()
    client = Client(profiles.get('host'),
                    api_version=profiles.get('api_version'),
                    verify_ssl_certs=profiles.get('verify'),
                    log_file='vcd.log',
                    log_requests=profiles.get('log_request'),
                    log_headers=profiles.get('log_header'),
                    log_bodies=profiles.get('log_body'))
    client.rehydrate(profiles)
    ctx.obj = {}
    ctx.obj['client'] = client
    ctx.obj['profiles'] = profiles
    if vdc_required:
        if not ctx.obj['profiles'].get('vdc_in_use') or \
           not ctx.obj['profiles'].get('vdc_href'):
            raise Exception('select a virtual datacenter')
예제 #3
0
파일: utils.py 프로젝트: tjecheva/vcd-cli
def restore_session(ctx):
    profiles = Profiles.load()
    token = profiles.get('token')
    if token is None or len(token) == 0:
        raise Exception('Can\'t restore session, please re-login.')
    if not profiles.get('verify'):
        if profiles.get('disable_warnings'):
            pass
        else:
            click.secho('InsecureRequestWarning: '
                        'Unverified HTTPS request is being made. '
                        'Adding certificate verification is strongly '
                        'advised.', fg='yellow', err=True)
        requests.packages.urllib3.disable_warnings()
    client = Client(profiles.get('host'),
                    api_version=profiles.get('api_version'),
                    verify_ssl_certs=profiles.get('verify'),
                    log_file='vcd.log',
                    log_requests=profiles.get('log_request'),
                    log_headers=profiles.get('log_header'),
                    log_bodies=profiles.get('log_body')
                    )
    client.rehydrate(profiles)
    ctx.obj = {}
    ctx.obj['client'] = client
    ctx.obj['profiles'] = profiles
예제 #4
0
파일: profile.py 프로젝트: vmware/vca-cli
def delete(ctx, module):
    try:
        profiles = Profiles.load()
        profiles.data['extensions'].remove(module)
        profiles.save()
        click.secho('Extension from module \'%s\' deleted.' % module)
    except Exception as e:
        stderr('Could not delete extension from module \'%s\'' % module, ctx)
예제 #5
0
def delete(ctx, module):
    try:
        profiles = Profiles.load()
        profiles.data['extensions'].remove(module)
        profiles.save()
        click.secho('Extension from module \'%s\' deleted.' % module)
    except Exception as e:
        stderr('Could not delete extension from module \'%s\'' % module, ctx)
예제 #6
0
파일: profile.py 프로젝트: vmware/vca-cli
def list_extensions(ctx):
    try:
        profiles = Profiles.load()
        if 'extensions' in profiles.data and \
                profiles.data['extensions'] is not None:
            for extension in profiles.data['extensions']:
                click.echo(extension)
    except Exception as e:
        stderr(e, ctx)
예제 #7
0
def list_extensions(ctx):
    try:
        profiles = Profiles.load()
        if 'extensions' in profiles.data and \
                profiles.data['extensions'] is not None:
            for extension in profiles.data['extensions']:
                click.echo(extension)
    except Exception as e:
        stderr(e, ctx)
예제 #8
0
파일: profile.py 프로젝트: vmware/vca-cli
def add(ctx, module):
    try:
        profiles = Profiles.load()
        if 'extensions' not in profiles.data or \
                profiles.data['extensions'] is None:
            profiles.data['extensions'] = []
        if module not in profiles.data['extensions']:
            profiles.data['extensions'].append(module)
            profiles.save()
            click.secho('Extension added from module \'%s\'.' % module)
        else:
            raise Exception('module already in the profile')
    except Exception as e:
        stderr('Could not add extension from module \'%s\'' % module, ctx)
예제 #9
0
def add(ctx, module):
    try:
        profiles = Profiles.load()
        if 'extensions' not in profiles.data or \
                profiles.data['extensions'] is None:
            profiles.data['extensions'] = []
        if module not in profiles.data['extensions']:
            profiles.data['extensions'].append(module)
            profiles.save()
            click.secho('Extension added from module \'%s\'.' % module)
        else:
            raise Exception('module already in the profile')
    except Exception as e:
        stderr('Could not add extension from module \'%s\'' % module, ctx)
예제 #10
0
def cse_restore_session(ctx, vdc_required=False) -> None:
    """Restores the session with vcd client with right server api version.

    Replace the vcd client in ctx.obj with new client created with server api
    version. Also saves the server api version in profiles.

    :param <click.core.Context> ctx: click context
    :param bool vdc_required: is vdc required or not
    :return:
    """
    # Always override the vcd_client by new client with CSE server api version.
    if type(ctx.obj) is not dict or not ctx.obj.get('client'):
        profiles = Profiles.load()
        token = profiles.get('token')
        if token is None or len(token) == 0:
            raise Exception('Can\'t restore session, please login again.')
        if not profiles.get('verify'):
            if not profiles.get('disable_warnings'):
                click.secho(
                    'InsecureRequestWarning: '
                    'Unverified HTTPS request is being made. '
                    'Adding certificate verification is strongly '
                    'advised.',
                    fg='yellow',
                    err=True)
            requests.packages.urllib3.disable_warnings()

        client = Client(
            profiles.get('host'),
            api_version=profiles.get('api_version'),
            verify_ssl_certs=profiles.get('verify'),
            log_file='vcd.log',
            log_requests=profiles.get('log_request'),
            log_headers=profiles.get('log_header'),
            log_bodies=profiles.get('log_body'))
        client.rehydrate_from_token(
            profiles.get('token'), profiles.get('is_jwt_token'))

        ctx.obj = {}
        ctx.obj['client'] = client

    _override_client(ctx)

    if vdc_required:
        if not ctx.obj['profiles'].get('vdc_in_use') or \
                not ctx.obj['profiles'].get('vdc_href'):
            raise Exception('select a virtual datacenter')
예제 #11
0
def load_user_plugins():
    profiles = Profiles.load()
    if 'extensions' in profiles.data and \
            profiles.data['extensions'] is not None:
        for extension in profiles.data['extensions']:
            try:
                __import__(extension)
            except ImportError:
                click.secho('Warning: the extension module \'%s\''
                            ' could not be imported.' % extension,
                            fg='yellow',
                            err=True)
            except Exception:
                click.secho('Warning: the extension module \'%s\''
                            ' could not be loaded.' % extension,
                            fg='yellow',
                            err=True)
예제 #12
0
def _override_client(ctx) -> None:
    """Replace the vcd client in ctx.obj with new one.

    New vcd client takes the CSE server_api_version as api_version param.
    Save profile also with 'cse_server_api_version' for subsequent commands.

    :param <click.core.Context> ctx: click context
    """
    profiles = Profiles.load()
    # if the key CSE_SERVER_RUNNING is not present in the profiles.yaml,
    # we make an assumption that CSE server is running
    is_cse_server_running = profiles.get(CSE_SERVER_RUNNING, default=True)
    cse_server_api_version = profiles.get(CSE_SERVER_API_VERSION)
    if not is_cse_server_running:
        restrict_cli_to_tkg_operations()
        ctx.obj['profiles'] = profiles
        return

    # Get server_api_version; save it in profiles if doesn't exist
    if not cse_server_api_version:
        try:
            system = syst.System(ctx.obj['client'])
            sys_info = system.get_info()
            cse_server_api_version = sys_info.get(CSE_SERVER_API_VERSION)
            profiles.set(CSE_SERVER_API_VERSION, cse_server_api_version)
            profiles.set(CSE_SERVER_RUNNING, True)
            profiles.save()
        except CseResponseError:
            # If request to CSE server times out
            profiles.set(CSE_SERVER_RUNNING, False)
            # restrict CLI for only TKG operations
            restrict_cli_to_tkg_operations()
            ctx.obj['profiles'] = profiles
            profiles.save()
            return
    client = Client(profiles.get('host'),
                    api_version=cse_server_api_version,
                    verify_ssl_certs=profiles.get('verify'),
                    log_file='vcd.log',
                    log_requests=profiles.get('log_request'),
                    log_headers=profiles.get('log_header'),
                    log_bodies=profiles.get('log_body'))
    client.rehydrate_from_token(profiles.get('token'),
                                profiles.get('is_jwt_token'))  # noqa: E501
    ctx.obj['client'] = client
    ctx.obj['profiles'] = profiles
예제 #13
0
def cse_restore_session(ctx) -> None:
    """Restores the session with vcd client with right server api version.

    Replace the vcd client in ctx.obj with new client created with server api
    version. Also saves the server api version in profiles.

    :param <click.core.Context> ctx: click context

    :return:
    """
    # Always override the vcd_client by new client with CSE server api version.
    if type(ctx.obj) is not dict or not ctx.obj.get('client'):
        CLIENT_LOGGER.debug('Restoring client from profile.')
        profiles = Profiles.load()
        token = profiles.get('token')
        if token is None or len(token) == 0:
            msg = "Can't restore session, please login again."
            CLIENT_LOGGER.debug(f"Missing Token : {msg}")
            raise Exception(msg)
        if not profiles.get('verify'):
            if not profiles.get('disable_warnings'):
                click.secho(
                    'InsecureRequestWarning: '
                    'Unverified HTTPS request is being made. '
                    'Adding certificate verification is strongly '
                    'advised.',
                    fg='yellow',
                    err=True)
            requests.packages.urllib3.disable_warnings()

        client = Client(profiles.get('host'),
                        api_version=profiles.get('api_version'),
                        verify_ssl_certs=profiles.get('verify'),
                        log_file='vcd.log',
                        log_requests=profiles.get('log_request'),
                        log_headers=profiles.get('log_header'),
                        log_bodies=profiles.get('log_body'))
        client.rehydrate_from_token(profiles.get('token'),
                                    profiles.get('is_jwt_token'))

        ctx.obj = {'client': client}
    else:
        CLIENT_LOGGER.debug('Reusing client from context.')

    _override_client(ctx)
def vcd_login_with_token(host):
    logging.basicConfig(level=logging.DEBUG)
    logging.info("INIT vcd_login_with_token")
    profiles = Profiles.load()
    token = profiles.get('token')
    client = Client(host,
                    api_version="27.0",
                    verify_ssl_certs=False,
                    log_file='vcd.log',
                    log_requests=True,
                    log_headers=True,
                    log_bodies=True)
    try:
        client.rehydrate_from_token(token)
        x = client._session.headers['x-vcloud-authorization']
        logging.info(" =====  X VCloud ========\n  \n" + x + "\n \n")
    except Exception as e:
        print('error occured', e)
예제 #15
0
파일: plugin.py 프로젝트: vmware/vca-cli
def load_user_plugins():
    profiles = Profiles.load()
    if 'extensions' in profiles.data and \
            profiles.data['extensions'] is not None:
        for extension in profiles.data['extensions']:
            try:
                __import__(extension)
            except ImportError:
                click.secho(
                    'Warning: the extension module \'%s\''
                    ' could not be imported.' % extension,
                    fg='yellow',
                    err=True)
            except Exception:
                click.secho(
                    'Warning: the extension module \'%s\''
                    ' could not be loaded.' % extension,
                    fg='yellow',
                    err=True)
def vcd_login_with_token(host):
    logging.basicConfig(level=logging.DEBUG)
    logging.info("INIT vcd_login_with_token")
    profiles = Profiles.load()
    token = profiles.get('token')
    client = Client(
        host,
        api_version="27.0",
        verify_ssl_certs=False,
        log_file='vcd.log',
        log_requests=True,
        log_headers=True,
        log_bodies=True)
    try:
        client.rehydrate_from_token(token)
        x = client._session.headers['x-vcloud-authorization']
        logging.info(" =====  X VCloud ========\n  \n" + x + "\n \n")
    except Exception as e:
        print('error occured', e)
예제 #17
0
파일: utils.py 프로젝트: vmware/vca-cli
def restore_session(ctx, vdc_required=False):
    if type(
            ctx.obj
    ) is dict and 'client' in ctx.obj and ctx.obj['client'] is not None:
        return
    profiles = Profiles.load()
    token = profiles.get('token')
    if token is None or len(token) == 0:
        raise Exception('Can\'t restore session, please login again.')
    if not profiles.get('verify'):
        if profiles.get('disable_warnings'):
            pass
        else:
            click.secho(
                'InsecureRequestWarning: '
                'Unverified HTTPS request is being made. '
                'Adding certificate verification is strongly '
                'advised.',
                fg='yellow',
                err=True)
        requests.packages.urllib3.disable_warnings()
    client = Client(
        profiles.get('host'),
        api_version=profiles.get('api_version'),
        verify_ssl_certs=profiles.get('verify'),
        log_file='vcd.log',
        log_requests=profiles.get('log_request'),
        log_headers=profiles.get('log_header'),
        log_bodies=profiles.get('log_body'))
    client.rehydrate(profiles)
    ctx.obj = {}
    ctx.obj['client'] = client
    ctx.obj['profiles'] = profiles
    if vdc_required:
        if not ctx.obj['profiles'].get('vdc_in_use') or \
           not ctx.obj['profiles'].get('vdc_href'):
            raise Exception('select a virtual datacenter')
def vcd_login(context, lc):
    logging.info("__INIT__vcd_login [%s]", lc)
    login_path = ""
    client = Client(
        lc.ip,
        api_version="27.0",
        verify_ssl_certs=not lc.allow_insecure_flag,
        log_file='vcd.log',
        log_requests=True,
        log_headers=True,
        log_bodies=True)
    try:
        if lc.use_vcd_cli_profile:
            login_path = "rehydrate_from_token"
            profiles = Profiles.load()
            token = profiles.get('token')
            client.rehydrate_from_token(token)

        else:
            login_path = "set_credentials"
            client.set_credentials(
                BasicLoginCredentials(lc.username, lc.org, lc.password))

        vref = VCDClientRef()
        vref.set_ref(client)
        logging.debug('LOGIN VIA :[{0}] ARG :[{1}]'.format(
            login_path, str(lc)))

        return client
    except Exception as e:
        traceback.print_exc()
        error_message = 'ERROR IN LOGIN .. Exception [{0}] LOGIN VIA :[{1}] ARG :[{2}]'.format(
            str(e), login_path, str(lc))
        error_message = error_message.replace('\n', ' ')
        context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
        context.set_details(error_message)
        raise
예제 #19
0
def vcd_login(context, lc):
    logging.info("__INIT__vcd_login [%s]", lc)
    login_path = ""
    client = Client(lc.ip,
                    api_version="27.0",
                    verify_ssl_certs=not lc.allow_insecure_flag,
                    log_file='vcd.log',
                    log_requests=True,
                    log_headers=True,
                    log_bodies=True)
    try:
        if lc.use_vcd_cli_profile:
            login_path = "rehydrate_from_token"
            profiles = Profiles.load()
            token = profiles.get('token')
            client.rehydrate_from_token(token)

        else:
            login_path = "set_credentials"
            client.set_credentials(
                BasicLoginCredentials(lc.username, lc.org, lc.password))

        vref = VCDClientRef()
        vref.set_ref(client)
        logging.debug('LOGIN VIA :[{0}] ARG :[{1}]'.format(
            login_path, str(lc)))

        return client
    except Exception as e:
        traceback.print_exc()
        error_message = 'ERROR IN LOGIN .. Exception [{0}] LOGIN VIA :[{1}] ARG :[{2}]'.format(
            str(e), login_path, str(lc))
        error_message = error_message.replace('\n', ' ')
        context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
        context.set_details(error_message)
        raise
예제 #20
0
def _override_client(ctx) -> None:
    """Replace the vcd client in ctx.obj with new one.

    New vcd client takes the CSE server_api_version as api_version param.
    Save profile also with 'cse_server_api_version' for subsequent commands.

    :param <click.core.Context> ctx: click context
    """
    profiles = Profiles.load()
    # if the key CSE_SERVER_RUNNING is not present in the profiles.yaml,
    # we make an assumption that CSE server is running
    is_cse_server_running = profiles.get(CSE_SERVER_RUNNING, default=True)
    cse_server_api_version = profiles.get(CSE_SERVER_API_VERSION)
    if not is_cse_server_running:
        CLIENT_LOGGER.debug(
            "CSE server not running as per profile, restricting CLI to only TKG operations."
        )  # noqa: E501
        restrict_cli_to_tkg_s_operations()
        ctx.obj['profiles'] = profiles
        return

    # Get server_api_version; save it in profiles if doesn't exist
    if not cse_server_api_version:
        try:
            system = syst.System(ctx.obj['client'])
            sys_info = system.get_info()

            is_pre_cse_3_1_server = False
            if CSE_SERVER_LEGACY_MODE not in sys_info or \
                    CSE_SERVER_SUPPORTED_API_VERSIONS not in sys_info:
                is_pre_cse_3_1_server = True

            if not is_pre_cse_3_1_server:
                is_cse_server_running_in_legacy_mode = \
                    sys_info.get(CSE_SERVER_LEGACY_MODE)
                cse_server_supported_api_versions = \
                    set(sys_info.get(CSE_SERVER_SUPPORTED_API_VERSIONS))
                cse_client_supported_api_versions = \
                    set(shared_constants.SUPPORTED_VCD_API_VERSIONS)

                common_supported_api_versions = \
                    list(cse_server_supported_api_versions.intersection(
                        cse_client_supported_api_versions))

                # ToDo: Instead of float use proper version comparison
                if is_cse_server_running_in_legacy_mode:
                    common_supported_api_versions = \
                        [float(x) for x in common_supported_api_versions
                            if float(x) < 35.0]
                else:
                    common_supported_api_versions = \
                        [float(x) for x in common_supported_api_versions
                            if float(x) >= 35.0]

                cse_server_api_version = \
                    str(max(common_supported_api_versions))
                CLIENT_LOGGER.debug(
                    f"Server api versions : {cse_server_supported_api_versions}, "  # noqa: E501
                    f"Client api versions : {cse_client_supported_api_versions}, "  # noqa: E501
                    f"Server in Legacy mode : {is_cse_server_running_in_legacy_mode}, "  # noqa: E501
                    f"Selected api version : {cse_server_api_version}.")
            else:
                cse_server_api_version = \
                    sys_info.get(CSE_SERVER_API_VERSION)
                CLIENT_LOGGER.debug(
                    "Pre CSE 3.1 server detected. Selected api version : "
                    f"{cse_server_api_version}.")

            profiles.set(CSE_SERVER_API_VERSION, cse_server_api_version)
            profiles.set(CSE_SERVER_RUNNING, True)
            profiles.save()
        except (requests.exceptions.Timeout, CseResponseError) as err:
            CLIENT_LOGGER.error(err, exc_info=True)
            CLIENT_LOGGER.debug(
                "Request to CSE server timed out. Restricting CLI to only TKG operations."
            )  # noqa: E501

            profiles.set(CSE_SERVER_RUNNING, False)
            restrict_cli_to_tkg_s_operations()
            ctx.obj['profiles'] = profiles
            profiles.save()
            return
    client = Client(profiles.get('host'),
                    api_version=cse_server_api_version,
                    verify_ssl_certs=profiles.get('verify'),
                    log_file='vcd.log',
                    log_requests=profiles.get('log_request'),
                    log_headers=profiles.get('log_header'),
                    log_bodies=profiles.get('log_body'))
    client.rehydrate_from_token(profiles.get('token'),
                                profiles.get('is_jwt_token'))  # noqa: E501
    ctx.obj['client'] = client
    ctx.obj['profiles'] = profiles
예제 #21
0
파일: login.py 프로젝트: vmware/vca-cli
def login(ctx, user, host, password, api_version, org, verify_ssl_certs,
          disable_warnings, vdc, session_id, use_browser_session):
    """Login to vCloud Director

\b
    Login to a vCloud Director service.
\b
    Examples
        vcd login mysp.com org1 usr1
            Login to host 'mysp.com'.
\b
        vcd login test.mysp.com org1 usr1 -i -w
            Login to a host with self-signed SSL certificate.
\b
        vcd login mysp.com org1 usr1 --use-browser-session
            Login using active session from browser.
\b
        vcd login session list chrome
            List active session ids from browser.
\b
        vcd login mysp.com org1 usr1 \\
            --session-id ee968665bf3412d581bbc6192508eec4
            Login using active session id.
\b
    Environment Variables
        VCD_PASSWORD
            If this environment variable is set, the command will use its value
            as the password to login and will not ask for one. The --password
            option has precedence over the environment variable.

    """

    if not verify_ssl_certs:
        if disable_warnings:
            pass
        else:
            click.secho(
                'InsecureRequestWarning: '
                'Unverified HTTPS request is being made. '
                'Adding certificate verification is strongly '
                'advised.',
                fg='yellow',
                err=True)
        requests.packages.urllib3.disable_warnings()
    if host == 'session' and org == 'list':
        sessions = []
        if user == 'chrome':
            cookies = browsercookie.chrome()
            for c in cookies:
                if c.name == 'vcloud_session_id':
                    sessions.append({'host': c.domain, 'session_id': c.value})
        stdout(sessions, ctx)
        return

    client = Client(
        host,
        api_version=api_version,
        verify_ssl_certs=verify_ssl_certs,
        log_file='vcd.log',
        log_requests=True,
        log_headers=True,
        log_bodies=True)
    try:
        if api_version is None:
            api_version = client.set_highest_supported_version()

        if session_id is not None or use_browser_session:
            if use_browser_session:
                browser_session_id = None
                cookies = browsercookie.chrome()
                for c in cookies:
                    if c.name == 'vcloud_session_id' and \
                       c.domain == host:
                        browser_session_id = c.value
                        break
                if browser_session_id is None:
                    raise Exception('Session not found in browser.')
                session_id = browser_session_id
            client.rehydrate_from_token(session_id)
        else:
            if password is None:
                password = click.prompt('Password', hide_input=True, type=str)
            client.set_credentials(BasicLoginCredentials(user, org, password))
        wkep = {}
        for endpoint in _WellKnownEndpoint:
            if endpoint in client._session_endpoints:
                wkep[endpoint.name] = client._session_endpoints[endpoint]
        profiles = Profiles.load()
        logged_in_org = client.get_org()
        org_href = logged_in_org.get('href')
        vdc_href = ''
        in_use_vdc = ''
        if vdc is None:
            for v in get_links(logged_in_org, media_type=EntityType.VDC.value):
                in_use_vdc = v.name
                vdc_href = v.href
                break
        else:
            for v in get_links(logged_in_org, media_type=EntityType.VDC.value):
                if vdc == v.name:
                    in_use_vdc = v.name
                    vdc_href = v.href
                    break
            if len(in_use_vdc) == 0:
                raise Exception('VDC not found')
        profiles.update(
            host,
            org,
            user,
            client._session.headers['x-vcloud-authorization'],
            api_version,
            wkep,
            verify_ssl_certs,
            disable_warnings,
            vdc=in_use_vdc,
            org_href=org_href,
            vdc_href=vdc_href,
            log_request=True,
            log_header=True,
            log_body=True,
            vapp='',
            vapp_href='')
        alt_text = '%s logged in, org: \'%s\', vdc: \'%s\'' % \
                   (user, org, in_use_vdc)
        stdout({
            'user': user,
            'org': org,
            'vdc': in_use_vdc,
            'logged_in': True
        }, ctx, alt_text)
    except Exception as e:
        try:
            profiles = Profiles.load()
            profiles.set('token', '')
        except Exception:
            pass
        stderr(e, ctx)
예제 #22
0
파일: profile.py 프로젝트: vmware/vca-cli
def info(ctx):
    try:
        profiles = Profiles.load()
        click.echo(yaml.dump(profiles.data, default_flow_style=False))
    except Exception as e:
        stderr(e, ctx)
예제 #23
0
def load_user_plugins():
    profiles = Profiles.load()
    if 'extensions' in profiles.data and len(profiles.data) > 0:
        for extension in profiles.data['extensions']:
            __import__(extension)
예제 #24
0
def login(ctx, user, host, password, api_version, org, verify_ssl_certs,
          disable_warnings, vdc, session_id, use_browser_session):
    """Login to vCloud Director

\b
    Login to a vCloud Director service.
\b
    Examples
        vcd login mysp.com org1 usr1
            Login to host 'mysp.com'.
\b
        vcd login test.mysp.com org1 usr1 -i -w
            Login to a host with self-signed SSL certificate.
\b
        vcd login mysp.com org1 usr1 --use-browser-session
            Login using active session from browser.
\b
        vcd login session list chrome
            List active session ids from browser.
\b
        vcd login mysp.com org1 usr1 \\
            --session-id ee968665bf3412d581bbc6192508eec4
            Login using active session id.
\b
    Environment Variables
        VCD_PASSWORD
            If this environment variable is set, the command will use its value
            as the password to login and will not ask for one. The --password
            option has precedence over the environment variable.

    """

    if not verify_ssl_certs:
        if disable_warnings:
            pass
        else:
            click.secho(
                'InsecureRequestWarning: '
                'Unverified HTTPS request is being made. '
                'Adding certificate verification is strongly '
                'advised.',
                fg='yellow',
                err=True)
        requests.packages.urllib3.disable_warnings()

    if host == 'session' and org == 'list':
        sessions = []
        if user == 'chrome':
            cookies = browsercookie.chrome()
            for c in cookies:
                if c.name == 'vcloud_session_id':
                    sessions.append({'host': c.domain, 'session_id': c.value})
        stdout(sessions, ctx)
        return

    client = Client(
        host,
        api_version=api_version,
        verify_ssl_certs=verify_ssl_certs,
        log_file='vcd.log',
        log_requests=True,
        log_headers=True,
        log_bodies=True)
    try:
        if session_id is not None or use_browser_session:
            if use_browser_session:
                browser_session_id = None
                cookies = browsercookie.chrome()
                for c in cookies:
                    if c.name == 'vcloud_session_id' and \
                       c.domain == host:
                        browser_session_id = c.value
                        break
                if browser_session_id is None:
                    raise Exception('Session not found in browser.')
                session_id = browser_session_id
            client.rehydrate_from_token(session_id)
        else:
            if password is None:
                password = click.prompt('Password', hide_input=True, type=str)
            client.set_credentials(BasicLoginCredentials(user, org, password))

        negotiated_api_version = client.get_api_version()

        profiles = Profiles.load()
        logged_in_org = client.get_org()
        org_href = logged_in_org.get('href')
        vdc_href = ''
        in_use_vdc = ''

        links = []
        if float(negotiated_api_version) < float(ApiVersion.VERSION_33.value):
            links = get_links(logged_in_org, media_type=EntityType.VDC.value)
        else:
            if logged_in_org.get('name') != 'System':
                links = client.get_resource_link_from_query_object(
                    logged_in_org, media_type=EntityType.RECORDS.value,
                    type='vdc')

        if vdc is None:
            if len(links) > 0:
                in_use_vdc = links[0].name
                vdc_href = links[0].href
        else:
            for v in links:
                if vdc == v.name:
                    in_use_vdc = v.name
                    vdc_href = v.href
                    break
            if len(in_use_vdc) == 0:
                raise Exception('VDC not found')

        token = client.get_access_token()
        is_jwt_token = True
        if not token:
            token = client.get_xvcloud_authorization_token()
            is_jwt_token = False

        profiles.update(
            host,
            org,
            user,
            token,
            negotiated_api_version,
            verify_ssl_certs,
            disable_warnings,
            vdc=in_use_vdc,
            org_href=org_href,
            vdc_href=vdc_href,
            log_request=True,
            log_header=True,
            log_body=True,
            vapp='',
            vapp_href='',
            is_jwt_token=is_jwt_token)

        alt_text = f"{user} logged in, org: '{org}', vdc: '{in_use_vdc}'"
        d = {
            'user': user,
            'org': org,
            'vdc': in_use_vdc,
            'logged_in': True
        }
        stdout(d, ctx, alt_text)
    except Exception as e:
        try:
            profiles = Profiles.load()
            profiles.set('token', '')
        except Exception:
            pass
        stderr(e, ctx)
예제 #25
0
파일: login.py 프로젝트: tjecheva/vcd-cli
def login(ctx, user, host, password, api_version, org,
          verify_ssl_certs, disable_warnings, vdc, session_id,
          use_browser_session):
    """Login to vCloud Director

\b
    Login to a vCloud Director service.
\b
    Examples
        vcd login mysp.com org1 usr1
            Login to host 'mysp.com'.
\b
        vcd login test.mysp.com org1 usr1 -i -w
            Login to a host with self-signed SSL certificate.
\b
        vcd login mysp.com org1 usr1 --use-browser-session
            Login using active session from browser.
\b
        vcd login session list chrome
            List active session ids from browser.
\b
        vcd login mysp.com org1 usr1 \\
            --session-id ee968665bf3412d581bbc6192508eec4
            Login using active session id.
\b
    Environment Variables
        VCD_PASSWORD
            If this environment variable is set, the command will use its value
            as the password to login and will not ask for one. The --password
            option has precedence over the environment variable.

    """

    if not verify_ssl_certs:
        if disable_warnings:
            pass
        else:
            click.secho('InsecureRequestWarning: '
                        'Unverified HTTPS request is being made. '
                        'Adding certificate verification is strongly '
                        'advised.', fg='yellow', err=True)
        requests.packages.urllib3.disable_warnings()
    if host == 'session' and org == 'list':
        sessions = []
        if user == 'chrome':
            cookies = browsercookie.chrome()
            for c in cookies:
                if c.name == 'vcloud_session_id':
                    sessions.append({'host': c.domain, 'session_id': c.value})
        stdout(sessions, ctx)
        return

    client = Client(host,
                    api_version=api_version,
                    verify_ssl_certs=verify_ssl_certs,
                    log_file='vcd.log',
                    log_requests=True,
                    log_headers=True,
                    log_bodies=True
                    )
    try:
        if api_version is None:
            api_version = client.set_highest_supported_version()

        if session_id is not None or use_browser_session:
            if use_browser_session:
                browser_session_id = None
                cookies = browsercookie.chrome()
                for c in cookies:
                    if c.name == 'vcloud_session_id' and \
                       c.domain == host:
                        browser_session_id = c.value
                        break
                if browser_session_id is None:
                    raise Exception('Session not found in browser.')
                session_id = browser_session_id
            client.rehydrate_from_token(session_id)
        else:
            if password is None:
                password = click.prompt('Password', hide_input=True, type=str)
            client.set_credentials(BasicLoginCredentials(user, org, password))
        wkep = {}
        for endpoint in _WellKnownEndpoint:
            if endpoint in client._session_endpoints:
                wkep[endpoint.name] = client._session_endpoints[endpoint]
        profiles = Profiles.load()
        logged_in_org = client.get_org()
        org_href = logged_in_org.get('href')
        vdc_href = ''
        in_use_vdc = ''
        if vdc is None:
            for v in get_links(logged_in_org, media_type=EntityType.VDC.value):
                in_use_vdc = v.name
                vdc_href = v.href
                break
        else:
            for v in get_links(logged_in_org, media_type=EntityType.VDC.value):
                if vdc == v.name:
                    in_use_vdc = v.name
                    vdc_href = v.href
                    break
            if len(in_use_vdc) == 0:
                raise Exception('VDC not found')
        profiles.update(host,
                        org,
                        user,
                        client._session.headers['x-vcloud-authorization'],
                        api_version,
                        wkep,
                        verify_ssl_certs,
                        disable_warnings,
                        vdc=in_use_vdc,
                        org_href=org_href,
                        vdc_href=vdc_href,
                        log_request=profiles.get('log_request', default=False),
                        log_header=profiles.get('log_header', default=False),
                        log_body=profiles.get('log_body', default=False),
                        vapp='',
                        vapp_href='')
        alt_text = '%s logged in, org: \'%s\', vdc: \'%s\'' % \
                   (user, org, in_use_vdc)
        stdout({'user': user, 'org': org,
                'vdc': in_use_vdc, 'logged_in': True}, ctx, alt_text)
    except Exception as e:
        try:
            profiles = Profiles.load()
            profiles.set('token', '')
        except Exception:
            pass
        stderr(e, ctx)
예제 #26
0
def info(ctx):
    try:
        profiles = Profiles.load()
        click.echo(yaml.dump(profiles.data, default_flow_style=False))
    except Exception as e:
        stderr(e, ctx)