def GetUserAndInstance(user_host, use_account_service):
    """Returns pair consiting of user name and instance name."""
    parts = user_host.split('@')
    if len(parts) == 1:
        if use_account_service:  # Using Account Service.
            user = gaia.GetDefaultAccountName()
        else:  # Uploading keys through metadata.
            user = ssh.GetDefaultSshUsername(warn_on_account_user=True)
        instance = parts[0]
        return user, instance
    if len(parts) == 2:
        return parts
    raise exceptions.ToolException(
        'Expected argument of the form [USER@]INSTANCE; received [{0}].'.
        format(user_host))
Example #2
0
    def CreateRequests(self, args):
        """Returns a list of requests necessary for describing users."""

        user = args.name
        if not user:
            user = gaia.GetDefaultAccountName(self.http)

        user_ref = self.clouduseraccounts_resources.Parse(
            user,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='clouduseraccounts.users')

        request = self.messages.ClouduseraccountsUsersGetRequest(
            project=self.project, user=user_ref.Name())

        return [request]
Example #3
0
    def Run(self, args):
        compute_holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        holder = base_classes.ComputeUserAccountsApiHolder(self.ReleaseTrack())
        client = holder.client
        name = args.name
        if not name:
            name = gaia.GetDefaultAccountName(client.http)

        user_ref = holder.resources.Parse(
            name,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='clouduseraccounts.users')

        if args.fingerprints:
            fingerprints = args.fingerprints
        else:
            fetcher = users_client.UserResourceFetcher(
                client, user_ref.project, client.http,
                compute_holder.client.batch_url)

            fingerprints = [
                k.fingerprint
                for k in fetcher.LookupUser(user_ref.Name()).publicKeys
            ]

        # Generate warning before deleting.
        prompt_list = [
            '[{0}]'.format(fingerprint) for fingerprint in fingerprints
        ]
        prompt_title = (
            'The following public keys will be removed from the user ' +
            user_ref.Name())
        utils.PromptForDeletionHelper(None,
                                      prompt_list,
                                      prompt_title=prompt_title)

        requests = []
        for fingerprint in fingerprints:
            request = (client.MESSAGES_MODULE.
                       ClouduseraccountsUsersRemovePublicKeyRequest(
                           project=user_ref.project,
                           fingerprint=fingerprint,
                           user=user_ref.Name()))
            requests.append((client.users, 'RemovePublicKey', request))

        return compute_holder.client.MakeRequests(requests)
Example #4
0
    def Run(self, args):
        compute_holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        holder = base_classes.ComputeUserAccountsApiHolder(self.ReleaseTrack())
        client = holder.client

        name = args.name
        if not name:
            name = gaia.GetDefaultAccountName(client.http)

        user_ref = holder.resources.Parse(
            name,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='clouduseraccounts.users')

        valid_key_types = [
            'ssh-rsa', 'ssh-dss', 'ecdsa-sha2-nistp256', 'ssh-ed25519'
        ]

        public_keys = []
        for key_file in args.public_key_files:
            key_text = file_utils.ReadFile(key_file, 'public-key')

            if key_text.split(' ', 1)[0] not in valid_key_types:
                raise exceptions.ToolException(
                    'You must specify a public key file that contains a key of a '
                    'supported form. Supported forms are {0}.'.format(
                        ', '.join(valid_key_types)))
            public_keys.append(key_text)

        formatted_expiration = time_util.CalculateExpiration(args.expire)

        requests = []
        for key in public_keys:
            public_key_message = client.MESSAGES_MODULE.PublicKey(
                description=args.description,
                expirationTimestamp=formatted_expiration,
                key=key)

            request = (client.MESSAGES_MODULE.
                       ClouduseraccountsUsersAddPublicKeyRequest(
                           project=user_ref.project,
                           publicKey=public_key_message,
                           user=user_ref.Name()))
            requests.append((client.users, 'AddPublicKey', request))

        return compute_holder.client.MakeRequests(requests)
Example #5
0
    def CreateRequests(self, args):

        name = args.name
        if not name:
            name = gaia.GetDefaultAccountName(self.http)

        user_ref = self.clouduseraccounts_resources.Parse(
            name,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='clouduseraccounts.users')

        if args.fingerprints:
            fingerprints = args.fingerprints
        else:
            fetcher = users_client.UserResourceFetcher(self.clouduseraccounts,
                                                       self.project, self.http,
                                                       self.batch_url)

            fingerprints = [
                k.fingerprint
                for k in fetcher.LookupUser(user_ref.Name()).publicKeys
            ]

        # Generate warning before deleting.
        prompt_list = [
            '[{0}]'.format(fingerprint) for fingerprint in fingerprints
        ]
        prompt_title = (
            'The following public keys will be removed from the user ' +
            user_ref.Name())
        utils.PromptForDeletionHelper(None,
                                      prompt_list,
                                      prompt_title=prompt_title)

        requests = []
        for fingerprint in fingerprints:
            request = self.messages.ClouduseraccountsUsersRemovePublicKeyRequest(
                project=self.project,
                fingerprint=fingerprint,
                user=user_ref.Name())
            requests.append(request)

        return requests
    def Run(self, args):
        """Issues requests necessary for describing users."""
        compute_holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        holder = base_classes.ComputeUserAccountsApiHolder(self.ReleaseTrack())
        client = holder.client

        user = args.name
        if not user:
            user = gaia.GetDefaultAccountName(
                compute_holder.client.apitools_client.http)

        user_ref = holder.resources.Parse(
            user,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='clouduseraccounts.users')

        request = client.MESSAGES_MODULE.ClouduseraccountsUsersGetRequest(
            project=user_ref.project, user=user_ref.Name())

        return compute_holder.client.MakeRequests([(client.users, 'Get',
                                                    request)])
Example #7
0
    def CreateRequests(self, args):

        name = args.name
        if not name:
            name = gaia.GetDefaultAccountName(self.http)

        user_ref = self.clouduseraccounts_resources.Parse(
            name, collection='clouduseraccounts.users')

        valid_key_types = [
            'ssh-rsa', 'ssh-dss', 'ecdsa-sha2-nistp256', 'ssh-ed25519'
        ]

        public_keys = []
        for key_file in args.public_key_files:
            key_text = file_utils.ReadFile(key_file, 'public-key')

            if key_text.split(' ', 1)[0] not in valid_key_types:
                raise exceptions.ToolException(
                    'You must specify a public key file that contains a key of a '
                    'supported form. Supported forms are {0}.'.format(
                        ', '.join(valid_key_types)))
            public_keys.append(key_text)

        formatted_expiration = time_util.CalculateExpiration(args.expire)

        requests = []
        for key in public_keys:
            public_key_message = self.messages.PublicKey(
                description=args.description,
                expirationTimestamp=formatted_expiration,
                key=key)

            request = self.messages.ClouduseraccountsUsersAddPublicKeyRequest(
                project=self.project,
                publicKey=public_key_message,
                user=user_ref.Name())
            requests.append(request)

        return requests
Example #8
0
    def Run(self, args):
        super(SshGA, self).Run(args)

        parts = args.user_host.split('@')
        if len(parts) == 1:
            if self._use_accounts_service:  # Using Account Service.
                user = gaia.GetDefaultAccountName(self.http)
            else:  # Uploading keys through metadata.
                user = ssh.GetDefaultSshUsername(warn_on_account_user=True)
            instance = parts[0]
        elif len(parts) == 2:
            user, instance = parts
        else:
            raise exceptions.ToolException(
                'Expected argument of the form [USER@]INSTANCE; received [{0}].'
                .format(args.user_host))

        instance_ref = instance_flags.SSH_INSTANCE_RESOLVER.ResolveResources(
            [instance],
            compute_scope.ScopeEnum.ZONE,
            args.zone,
            self.resources,
            scope_lister=flags.GetDefaultScopeLister(self.compute_client,
                                                     self.project))[0]
        instance = self.GetInstance(instance_ref)
        external_ip_address = ssh_utils.GetExternalIPAddress(instance)

        ssh_args = [self.env.ssh]
        if not args.plain:
            ssh_args.extend(ssh.GetDefaultFlags(self.keys.key_file))
            # Allocates a tty if no command was provided and a container was provided.
            if args.container and not args.command:
                ssh_args.append('-t')

        if args.ssh_flag:
            for flag in args.ssh_flag:
                for flag_part in flag.split():  # We want grouping here
                    dereferenced_flag = (flag_part.replace(
                        '%USER%', user).replace('%INSTANCE%',
                                                external_ip_address))
                    ssh_args.append(dereferenced_flag)

        host_key_alias = self.HostKeyAlias(instance)
        ssh_args.extend(
            ssh.GetHostKeyArgs(host_key_alias, args.plain,
                               args.strict_host_key_checking))

        ssh_args.append(ssh.UserHost(user, external_ip_address))

        if args.ssh_args:
            ssh_args.extend(args.ssh_args)
        if args.container:
            ssh_args.append('--')
            ssh_args.append('container_exec')
            ssh_args.append(args.container)
            # Runs the given command inside the given container if --command was
            # specified, otherwise runs /bin/sh.
            if args.command:
                ssh_args.append(args.command)
            else:
                ssh_args.append('/bin/sh')

        elif args.command:
            if not platforms.OperatingSystem.IsWindows():
                ssh_args.append('--')
            ssh_args.append(args.command)

        # Don't use strict error checking for ssh: if the executed command fails, we
        # don't want to consider it an error. We do, however, want to propagate its
        # return code.
        return_code = self.ActuallyRun(
            args,
            ssh_args,
            user,
            instance,
            instance_ref.project,
            strict_error_checking=False,
            use_account_service=self._use_accounts_service)
        if return_code:
            # Can't raise an exception because we don't want any "ERROR" message
            # printed; the output from `ssh` will be enough.
            sys.exit(return_code)