向 SFTP 服务器添加用户

本文档介绍了如何向 Cloud FTP 服务器添加用户。外部合作伙伴和内部利益相关方等用户可以使用该服务器安全地向 Cloud Storage 传输文件以及从 Cloud Storage 传输文件。

概括来讲,向 SFTP 服务器添加用户的步骤如下:

  1. 为用户配置权限。
  2. 创建 SFTP 用户并将其目录映射到 Cloud Storage 存储桶。

如需了解创建服务器的步骤,请参阅创建外部 SFTP 服务器和创建内部 SFTP 服务器。

注意事项

  • 您最多可以向用户授予对 10 个存储桶的访问权限。

  • 一个用户最多可以有 10 个公钥。

准备工作

  1. 创建一个或多个 Cloud Storage 存储桶,用于存储用户将要处理的数据(如果这些存储桶尚不存在)。

  2. 从用户将用于连接到服务器的每个 SSH 密钥对中获取用户的公钥。

    如果用户没有 SSH 密钥对,请按照以下步骤生成一个。

    生成 SSH 密钥对

    您需要哪种密钥格式?

    您需要的密钥格式取决于您用于连接到 SFTP 服务器的客户端。如需了解详情,请参阅支持的 SFTP 客户端。

    PEM 格式

    1. 如需创建 OpenSSH 密钥对(PEM 格式),请使用 ssh-keygen 实用程序。

      在将连接到 SFTP 服务器的客户端机器上,运行以下命令:

      ssh-keygen -t rsa -b 4096 -f ~/.ssh/KEY_PAIR_NAME

      将 KEY_PAIR_NAME 替换为密钥对的名称,例如 sftp_user_key。

    2. 提取公钥:

      cat ~/.ssh/KEY_PAIR_NAME.pub

    PPK 格式

    1. 如需创建 PuTTY 密钥对(PPK 格式),请使用 PuTTYgen 工具。

      在将连接到 SFTP 服务器的客户端机器上,运行以下命令:

      puttygen -t rsa -b 4096 -o KEY_PAIR_NAME.ppk

      将 KEY_PAIR_NAME 替换为密钥对的名称,例如 sftp_user_key。

    2. 提取公钥:

      puttygen -L KEY_PAIR_NAME.ppk

所需的角色

如需获得添加 SFTP 用户所需的权限,请让您的管理员为您授予项目的 FTP Admin (roles/ftp.admin) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。

此预定义角色包含添加 SFTP 用户所需的 ftp.users.create 权限。

您也可以使用自定义角色或其他预定义角色来获取此权限。

为用户配置权限

  1. 安装 Google Cloud CLI,然后 使用联合身份登录 gcloud CLI。 登录后,运行以下命令来初始化 Google Cloud CLI:

    gcloud init
  2. 设置项目:

    gcloud config set project PROJECT_ID

    将 PROJECT_ID 替换为包含 SFTP 服务器的项目 ID。

  3. 如果服务账号尚不存在,请为用户创建一个服务账号。服务账号代表用户访问 Cloud Storage 资源。

    gcloud iam service-accounts create USERNAME-sa \
        --description="USERNAME SFTP Service Account" \
        --display-name="USERNAME SFTP Service Account"

    将 USERNAME 替换为 SFTP 用户的唯一用户名。用户名必须以小写字母开头,可以包含小写字母、数字或连字符。长度上限为 32 个字符。

    成功后,系统会显示类似 Created service account [example-userid-sa] 的消息。

  4. 向创建 SFTP 用户的管理员授予 IAM 角色:

    1. 为自己授予 Service Account User (roles/iam.serviceAccountUser) 角色:

      gcloud iam service-accounts add-iam-policy-binding USERNAME-sa@PROJECT_ID. \
          --member="user:ADMINISTRATOR_EMAIL" \
          --role="roles/iam.serviceAccountUser"

      将 ADMINISTRATOR_EMAIL 替换为创建 SFTP 用户的主账号的邮箱。如果您要创建用户(而不是应用),则此值是您用于访问 Google Cloud的电子邮件地址。

      成功后,系统会显示如下所示的消息:

      Updated IAM policy for serviceAccount [example-userid-sa@example-project.].
      bindings:
      - members:
      - user:admin@example.com
      role: roles/iam.serviceAccountUser
      etag: BwZJk7OiSzw=
      version: 1
      
    2. 为自己授予存储桶的 Storage Bucket Viewer (roles/storage.bucketViewer) 角色:

      gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
          --member="user:ADMINISTRATOR_EMAIL" \
          --role="roles/storage.bucketViewer"

      将 BUCKET_NAME 替换为存储桶的名称。

      对于用户需要访问的每个存储桶,重复此步骤。

    3. 为自己授予存储桶的 Storage Object Viewer (roles/storage.objectViewer) 角色:

      gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
          --member="user:ADMINISTRATOR_EMAIL" \
          --role="roles/storage.objectViewer"

      对于用户需要访问的每个存储桶,重复此步骤。

  5. 向用户的服务账号授予访问存储桶所需的 IAM 角色:

    gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
        --member="serviceAccount:USERNAME-sa@PROJECT_ID." \
        --role="ROLE"

    将 ROLE 替换为以下某个 IAM 角色:

    • 如需只读权限,请使用 roles/storage.objectViewer 角色。
    • 如需读写权限,请使用 roles/storage.objectAdmin 角色。

    对于用户需要访问的每个存储桶,重复此步骤。

  6. 授权 Cloud FTP 服务代理为用户的服务账号生成令牌:

    1. 获取服务器的服务代理的邮箱。 如需了解相关步骤,请参阅获取服务器的详细信息。

    2. 为 Cloud FTP 服务代理授权:

      gcloud iam service-accounts add-iam-policy-binding USERNAME-sa@PROJECT_ID. \
          --member="serviceAccount:SERVICE_AGENT_EMAIL" \
          --role="roles/iam.serviceAccountTokenCreator"

      将 SERVICE_AGENT_EMAIL 替换为服务代理的电子邮件地址。

接下来,创建用户。

创建 SFTP 服务器用户

为用户配置权限后,您需要创建用户,并将其目录映射到一个或多个 Cloud Storage 存储桶。

gcloud

  1. 如需为 SFTP 服务器创建用户,请运行 gcloud alpha storage ftp users create 命令。

    在使用下面的命令数据之前,请先进行以下替换:

    • CREDENTIAL_NAME:用于标识用户凭据的唯一名称。
    • SSH_PUBLIC_KEY:用户的 SSH 公钥正文,采用 OpenSSH 格式。例如 ssh-rsa AAAAB3NzaC1ycRexample...。
    • USERNAME:SFTP 用户的用户名。
    • SERVICE_ACCOUNT:用户的服务账号。例如 username-sa@example-project.。
    • LOCATION_ID:服务器的位置,例如 us-west1。
    • SERVER_ID:服务器 ID。
    • BUCKET_NAME:SFTP 用户获准访问的存储桶的名称,例如 example-bucket。省略 gs://。
    • (可选)BUCKET_PREFIX:存储桶中要设置为此目录映射的根目录的文件夹的路径。 如果您省略 bucket_prefix 属性,Cloud FTP 会使用存储桶根目录。
    • DIRECTORY:向 SFTP 用户显示的逻辑着陆目录路径。 例如 /home/uploads。

      如果您映射多个存储桶或文件夹,请为每个映射提供唯一的目录路径。

      不支持嵌套逻辑目录。如果您为某个目录提供了多个映射,请以扁平结构而非嵌套结构提供这些目录。例如,使用 /dir1 和 /dir2,而不是 /dir1 和 /dir1/dir2。

    • SFTP_PERMISSION:目录的访问权限级别。对于只读访问权限,请将此值设置为 READ_ONLY。如需读写访问权限,请将此值设置为 READ_WRITE。

    请注意以下几点:

    • 如需向用户授予对多个映像桶的访问权限,请多次提供 --storage-directory-mapping 标志,并为每个映像桶提供目录映射。
    • 如需为用户配置多个公钥,请在 credentials.json 文件中提供多个凭据。

    将以下内容保存在名为 credentials.json 的文件中:

    [
      {
        "credentialName": "CREDENTIAL_NAME",
        "credentialType": "PUBLIC_KEY",
        "sshPublicKeyBody": "SSH_PUBLIC_KEY"
      }
    ]

    执行以下命令:

    Linux、macOS 或 Cloud Shell

    gcloud alpha storage ftp users create USERNAME \
        --customer-service-account=SERVICE_ACCOUNT --location=LOCATION_ID \
        --server=SERVER_ID \
        --storage-directory-mapping=bucket=BUCKET_NAME,bucket_prefix=BUCKET_PREFIX,directory=DIRECTORY,permission=SFTP_PERMISSION \
        --user-credentials-from-file=credentials.json

    Windows (PowerShell)

    gcloud alpha storage ftp users create USERNAME `
        --customer-service-account=SERVICE_ACCOUNT --location=LOCATION_ID `
        --server=SERVER_ID `
        --storage-directory-mapping=bucket=BUCKET_NAME,bucket_prefix=BUCKET_PREFIX,directory=DIRECTORY,permission=SFTP_PERMISSION `
        --user-credentials-from-file=credentials.json

    Windows (cmd.exe)

    gcloud alpha storage ftp users create USERNAME ^
        --customer-service-account=SERVICE_ACCOUNT --location=LOCATION_ID ^
        --server=SERVER_ID ^
        --storage-directory-mapping=bucket=BUCKET_NAME,bucket_prefix=BUCKET_PREFIX,directory=DIRECTORY,permission=SFTP_PERMISSION ^
        --user-credentials-from-file=credentials.json
    创建用户需要几秒钟的时间。

  2. 向用户提供以下信息,以便他们连接到服务器:

    • 用户的 SFTP 用户名。

    • 服务器的访问权限配置,具体取决于服务器类型:

      • 对于外部服务器,为服务器的 IP 地址。

      • 对于内部服务器,为服务器的服务连接的 URI。

      如需了解获取服务器访问配置的步骤,请参阅获取服务器的详细信息。

    • (可选)服务器的密钥指纹。

REST

  1. 如需为 SFTP 服务器创建用户,请使用 servers.users.create 方法。

    在使用任何请求数据之前,请先进行以下替换:

    • PROJECT_ID:服务器的 Google Cloud 项目 ID。
    • LOCATION_ID:服务器的位置,例如 us-west1。
    • SERVER_ID:服务器 ID。
    • USERNAME:SFTP 用户的用户名。
    • BUCKET_NAME:SFTP 用户获准访问的存储桶的名称,例如 example-bucket。省略 gs://。
    • (可选)BUCKET_PREFIX:存储桶中要设置为此目录映射的根目录的文件夹的路径。 如果您省略此值,Cloud FTP 将使用存储桶根目录。
    • DIRECTORY:向 SFTP 用户显示的逻辑着陆目录路径。 例如 /home/uploads。 如果您省略此值,则 Cloud FTP 会将着陆目录设置为 /。

      如果您映射多个存储桶或文件夹,请为每个映射提供唯一的目录路径。

      不支持嵌套逻辑目录。如果您为某个目录提供了多个映射,请以扁平结构而非嵌套结构提供这些目录。例如,使用 /dir1 和 /dir2,而不是 /dir1 和 /dir1/dir2。

    • SFTP_PERMISSION:目录的访问权限级别。对于只读访问权限,请将此值设置为 READ_ONLY。如需读写权限,请将此值设置为 READ_WRITE。
    • SERVICE_ACCOUNT:用户的服务账号。例如 username-sa@example-project.。
    • CREDENTIAL_NAME:用于标识用户凭据的唯一名称。
    • SSH_PUBLIC_KEY:用户的 SSH 公钥正文,采用 OpenSSH 格式。例如 ssh-rsa AAAAB3NzaC1ycRexample...。

    请注意以下几点:

    • 如需向用户授予对多个存储桶的访问权限,请在 storageDirectoryMappings 列表中提供多个存储桶映射。
    • 如需为用户配置多个公钥,请在 userCredentials 列表中提供多个凭据。

    HTTP 方法和网址:

    POST https://ftp.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/servers/SERVER_ID/users?userId=USERNAME

    请求 JSON 正文:

    {
      "storageDirectoryMappings": [
        {
          "bucket": "BUCKET_NAME",
          "bucketPrefix": "BUCKET_PREFIX",
          "directory": "DIRECTORY",
          "permission": "SFTP_PERMISSION"
        }
      ],
      "customerServiceAccount": "SERVICE_ACCOUNT",
      "userCredentials": [
        {
          "credentialName": "CREDENTIAL_NAME",
          "credentialType": "PUBLIC_KEY",
          "sshPublicKeyBody": "SSH_PUBLIC_KEY"
        }
      ]
    }
    

    如需发送您的请求,请展开以下选项之一:

    响应会识别长时间运行的操作。 创建用户需要几秒钟的时间。

  2. 向用户提供以下信息,以便他们连接到服务器:

    • 用户的 SFTP 用户名。

    • 服务器的访问权限配置,具体取决于服务器类型:

      • 对于外部服务器,为服务器的 IP 地址。

      • 对于内部服务器,为服务器的服务连接的 URI。

      如需了解获取服务器访问配置的步骤,请参阅获取服务器的详细信息。

    • (可选)服务器的密钥指纹。

客户端库

C#

如需了解如何安装和使用 Cloud FTP 客户端库,请参阅 Cloud FTP 客户端库。 如需了解详情,请参阅 Cloud FTP C# API 参考文档。

如需向 Cloud FTP 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。

using Google.Cloud.Ftp.V1;
using Google.LongRunning;
using System.Threading.Tasks;

public sealed partial class GeneratedCloudFtpClientSnippets
{
    /// <summary>Snippet for CreateUserAsync</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public async Task CreateUserAsync()
    {
        // Create client
        CloudFtpClient cloudFtpClient = await CloudFtpClient.CreateAsync();
        // Initialize request argument(s)
        string parent = "projects/[PROJECT]/locations/[LOCATION]/servers/[SERVER]";
        User user = new User();
        string userId = "";
        // Make the request
        Operation<User, OperationMetadata> response = await cloudFtpClient.CreateUserAsync(parent, user, userId);

        // Poll until the returned long-running operation is complete
        Operation<User, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
        // Retrieve the operation result
        User result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<User, OperationMetadata> retrievedResponse = await cloudFtpClient.PollOnceCreateUserAsync(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            User retrievedResult = retrievedResponse.Result;
        }
    }
}

Go

如需了解如何安装和使用 Cloud FTP 客户端库,请参阅 Cloud FTP 客户端库。 如需了解详情,请参阅 Cloud FTP Go API 参考文档。

如需向 Cloud FTP 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。


//go:build examples

package main

import (
	"context"

	ftp "cloud.google.com/go/ftp/apiv1"
	ftppb "cloud.google.com/go/ftp/apiv1/ftppb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := ftp.NewCloudFtpRESTClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &ftppb.CreateUserRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/ftp/apiv1/ftppb#CreateUserRequest.
	}
	op, err := c.CreateUser(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

如需了解如何安装和使用 Cloud FTP 客户端库,请参阅 Cloud FTP 客户端库。 如需了解详情,请参阅 Cloud FTP Java API 参考文档。

如需向 Cloud FTP 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

import com.google.api.core.ApiFuture;
import com.google.cloud.ftp.v1.CloudFtpClient;
import com.google.cloud.ftp.v1.CreateUserRequest;
import com.google.cloud.ftp.v1.ServerName;
import com.google.cloud.ftp.v1.User;
import com.google.longrunning.Operation;

public class AsyncCreateUser {

  public static void main(String[] args) throws Exception {
    asyncCreateUser();
  }

  public static void asyncCreateUser() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CloudFtpClient cloudFtpClient = CloudFtpClient.create()) {
      CreateUserRequest request =
          CreateUserRequest.newBuilder()
              .setParent(ServerName.of("[PROJECT]", "[LOCATION]", "[SERVER]").toString())
              .setUserId("userId-836030906")
              .setUser(User.newBuilder().build())
              .setRequestId("requestId693933066")
              .build();
      ApiFuture<Operation> future = cloudFtpClient.createUserCallable().futureCall(request);
      // Do something.
      Operation response = future.get();
    }
  }
}

Node.js

如需了解如何安装和使用 Cloud FTP 客户端库,请参阅 Cloud FTP 客户端库。 如需了解详情,请参阅 Cloud FTP Node.js API 参考文档。

如需向 Cloud FTP 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  Required. Value for parent.
 */
// const parent = 'abc123'
/**
 *  Required. A unique user ID for the SFTP user. The user ID must start with a
 *  lowercase letter and can include lowercase letters, numbers, or hyphens.
 */
// const userId = 'abc123'
/**
 *  Required. The resource being created
 */
// const user = {}
/**
 *  Optional. An optional request ID to identify requests. Specify a unique
 *  request ID so that if you must retry your request, the server will know to
 *  ignore the request if it has already been completed. The server will
 *  guarantee that for at least 60 minutes since the first request.
 *  For example, consider a situation where you make an initial request and the
 *  request times out. If you make the request again with the same request
 *  ID, the server can check if original operation with the same request ID
 *  was received, and if so, will ignore the second request. This prevents
 *  clients from accidentally creating duplicate commitments.
 *  The request ID must be a valid UUID with the exception that zero UUID is
 *  not supported (00000000-0000-0000-0000-000000000000).
 */
// const requestId = 'abc123'

// Imports the Ftp library
const {CloudFtpClient} = require('@google-cloud/ftp').v1;

// Instantiates a client
const ftpClient = new CloudFtpClient();

async function callCreateUser() {
  // Construct request
  const request = {
    parent,
    userId,
    user,
  };

  // Run request
  const [operation] = await ftpClient.createUser(request);
  const [response] = await operation.promise();
  console.log(response);
}

callCreateUser();

PHP

如需了解如何安装和使用 Cloud FTP 客户端库,请参阅 Cloud FTP 客户端库。 如需了解详情,请参阅 Cloud FTP PHP API 参考文档。

如需向 Cloud FTP 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证。

use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Ftp\V1\Client\CloudFtpClient;
use Google\Cloud\Ftp\V1\CreateUserRequest;
use Google\Cloud\Ftp\V1\StorageDirectoryMapping;
use Google\Cloud\Ftp\V1\StorageDirectoryMapping\Permission;
use Google\Cloud\Ftp\V1\User;
use Google\Cloud\Ftp\V1\UserCredential;
use Google\Cloud\Ftp\V1\UserCredential\Type;
use Google\Rpc\Status;

/**
 * Creates a new User in a given project and location and Server.
 *
 * @param string $formattedParent                        Value for parent. Please see
 *                                                       {@see CloudFtpClient::serverName()} for help formatting this field.
 * @param string $userId                                 A unique user ID for the SFTP user. The user ID must start with a
 *                                                       lowercase letter and can include lowercase letters, numbers, or hyphens.
 * @param string $userCustomerServiceAccount             Service account in customer project attached to this SFTP User.
 * @param string $userUserCredentialsCredentialName      Name of the user credential.
 * @param int    $userUserCredentialsCredentialType      Type of credential.
 * @param string $userStorageDirectoryMappingsBucket     Name of the bucket.
 * @param string $userStorageDirectoryMappingsDirectory  Directory where the user lands in the SFTP server.
 * @param int    $userStorageDirectoryMappingsPermission Permission to the bucket.
 */
function create_user_sample(
    string $formattedParent,
    string $userId,
    string $userCustomerServiceAccount,
    string $userUserCredentialsCredentialName,
    int $userUserCredentialsCredentialType,
    string $userStorageDirectoryMappingsBucket,
    string $userStorageDirectoryMappingsDirectory,
    int $userStorageDirectoryMappingsPermission
): void {
    // Create a client.
    $cloudFtpClient = new CloudFtpClient();

    // Prepare the request message.
    $userCredential = (new UserCredential())
        ->setCredentialName($userUserCredentialsCredentialName)
        ->setCredentialType($userUserCredentialsCredentialType);
    $userUserCredentials = [$userCredential];
    $storageDirectoryMapping = (new StorageDirectoryMapping())
        ->setBucket($userStorageDirectoryMappingsBucket)
        ->setDirectory($userStorageDirectoryMappingsDirectory)
        ->setPermission($userStorageDirectoryMappingsPermission);
    $userStorageDirectoryMappings = [$storageDirectoryMapping];
    $user = (new User())
        ->setCustomerServiceAccount($userCustomerServiceAccount)
        ->setUserCredentials($userUserCredentials)
        ->setStorageDirectoryMappings($userStorageDirectoryMappings);
    $request = (new CreateUserRequest())
        ->setParent($formattedParent)
        ->setUserId($userId)
        ->setUser($user);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $cloudFtpClient->createUser($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var User $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = CloudFtpClient::serverName('[PROJECT]', '[LOCATION]', '[SERVER]');
    $userId = '[USER_ID]';
    $userCustomerServiceAccount = '[CUSTOMER_SERVICE_ACCOUNT]';
    $userUserCredentialsCredentialName = '[CREDENTIAL_NAME]';
    $userUserCredentialsCredentialType = Type::TYPE_UNSPECIFIED;
    $userStorageDirectoryMappingsBucket = '[BUCKET]';
    $userStorageDirectoryMappingsDirectory = '[DIRECTORY]';
    $userStorageDirectoryMappingsPermission = Permission::PERMISSION_UNSPECIFIED;

    create_user_sample(
        $formattedParent,
        $userId,
        $userCustomerServiceAccount,
        $userUserCredentialsCredentialName,
        $userUserCredentialsCredentialType,
        $userStorageDirectoryMappingsBucket,
        $userStorageDirectoryMappingsDirectory,
        $userStorageDirectoryMappingsPermission
    );
}

Python

如需了解如何安装和使用 Cloud FTP 客户端库,请参阅 Cloud FTP 客户端库。 如需了解详情,请参阅 Cloud FTP Python API 参考文档。

如需向 Cloud FTP 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import ftp_v1


def sample_create_user():
    # Create a client
    client = ftp_v1.CloudFtpClient()

    # Initialize request argument(s)
    user = ftp_v1.User()
    user.customer_service_account = "customer_service_account_value"
    user.user_credentials.credential_name = "credential_name_value"
    user.user_credentials.credential_type = "PUBLIC_KEY"
    user.storage_directory_mappings.bucket = "bucket_value"
    user.storage_directory_mappings.directory = "directory_value"
    user.storage_directory_mappings.permission = "READ_WRITE"

    request = ftp_v1.CreateUserRequest(
        parent="parent_value",
        user_id="user_id_value",
        user=user,
    )

    # Make the request
    operation = client.create_user(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

Ruby

如需了解如何安装和使用 Cloud FTP 客户端库,请参阅 Cloud FTP 客户端库。 如需了解详情,请参阅 Cloud FTP Ruby API 参考文档。

如需向 Cloud FTP 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

require "google/cloud/ftp/v1"

##
# Snippet for the create_user call in the CloudFtp service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::Ftp::V1::CloudFtp::Rest::Client#create_user.
#
def create_user
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Ftp::V1::CloudFtp::Rest::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Ftp::V1::CreateUserRequest.new

  # Call the create_user method.
  result = client.create_user request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

后续步骤