將使用者新增至 SFTP 伺服器

本文說明如何將使用者新增至 Cloud FTP 伺服器。外部合作夥伴和內部利害關係人等使用者,可以透過伺服器安全地將檔案傳輸至 Cloud Storage,或從 Cloud Storage 傳輸檔案。

如要將使用者新增至 SFTP 伺服器,大致步驟如下:

  1. 設定使用者的權限。
  2. 建立 SFTP 使用者,並將目錄對應至 Cloud Storage bucket。

如要瞭解如何建立伺服器,請參閱「建立外部安全檔案傳輸通訊協定伺服器」和「建立內部安全檔案傳輸通訊協定伺服器」。

注意事項

  • 您最多可以授予使用者 10 個 bucket 的存取權。

  • 每位使用者最多可有 10 個公開金鑰。

事前準備

  1. 建立一或多個 Cloud Storage bucket,用於儲存使用者要處理的資料 (如果 bucket 尚未建立)。

  2. 從使用者用來連線至伺服器的每個安全殼層金鑰組中,取得使用者的公開金鑰。

    如果使用者沒有安全殼層金鑰組,請按照下列步驟產生。

    產生安全殼層 (SSH) 金鑰組

    您需要哪種金鑰格式?

    您需要的金鑰格式取決於用來連線至安全檔案傳輸通訊協定伺服器的用戶端。詳情請參閱「支援的 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 管理員 」(roles/ftp.admin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

這個預先定義的角色具備 ftp.users.create 權限,可新增 SFTP 使用者。

您或許還可透過自訂角色或其他預先定義的角色取得這項權限。

設定使用者權限

  1. 安裝 Google Cloud CLI。 安裝完成後,請執行下列指令,初始化 Google Cloud CLI:

    gcloud init

    若您採用的是外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI。

  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. 將 IAM 角色授予建立 SFTP 使用者的管理員:

    1. 將服務帳戶使用者 (roles/iam.serviceAccountUser) 角色授予自己:

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

      將 ADMINISTRATOR_EMAIL 替換為建立 SFTP 使用者的主體電子郵件地址。如果您建立的是使用者 (而非應用程式),這個值就是您用來存取 Google Cloud的電子郵件地址。

      如果成功,系統會顯示類似以下的訊息:

      Updated IAM policy for serviceAccount [example-userid-sa@example-project.iam.gserviceaccount.com].
      bindings:
      - members:
      - user:admin@example.com
      role: roles/iam.serviceAccountUser
      etag: BwZJk7OiSzw=
      version: 1
      
    2. 在 bucket 中授予自己 Storage bucket 檢視者 (roles/storage.bucketViewer) 角色:

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

      將 BUCKET_NAME 替換為 bucket 名稱。

      針對使用者需要存取的每個值區,重複執行這個步驟。

    3. 在 bucket 授予自己 Storage 物件檢視者 (roles/storage.objectViewer) 角色:

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

      針對使用者需要存取的每個 bucket 重複執行這個步驟。

  5. 將存取 bucket 所需的 IAM 角色授予使用者的服務帳戶:

    gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
        --member="serviceAccount:USERNAME-sa@PROJECT_ID.iam.gserviceaccount.com" \
        --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.iam.gserviceaccount.com \
          --member="serviceAccount:SERVICE_AGENT_EMAIL" \
          --role="roles/iam.serviceAccountTokenCreator"

      將 SERVICE_AGENT_EMAIL 替換為服務代理的電子郵件地址。

接下來,請建立使用者。

建立安全檔案傳輸通訊協定伺服器使用者

設定使用者權限後,請建立使用者,並將其目錄對應至一或多個 Cloud Storage bucket。

gcloud

  1. 如要為 SFTP 伺服器建立使用者,請執行 gcloud alpha storage ftp users create 指令。

    使用下列任何指令資料前,請先替換以下項目:

    • CREDENTIAL_NAME:用來識別使用者憑證的專屬名稱。
    • SSH_PUBLIC_KEY:使用者安全殼層公開金鑰的主體,採用 OpenSSH 格式。例如 ssh-rsa AAAAB3NzaC1ycRexample...。
    • USERNAME:SFTP 使用者的使用者名稱。
    • SERVICE_ACCOUNT:使用者的服務帳戶。例如:username-sa@example-project.iam.gserviceaccount.com。
    • LOCATION_ID:伺服器的位置,例如 us-west1。
    • SERVER_ID:伺服器 ID。
    • BUCKET_NAME:SFTP 使用者有權存取的 bucket 名稱,例如 example-bucket。刪除 gs://。
    • (選用) BUCKET_PREFIX:要設為這個目錄對應根目錄的 bucket 內資料夾路徑。 如果省略 bucket_prefix 屬性,Cloud FTP 會使用 bucket 根目錄。
    • DIRECTORY:向 SFTP 使用者顯示的邏輯登陸目錄路徑。 例如:/home/uploads。

      如果您對應多個 bucket 或資料夾,請為每個對應提供不重複的目錄路徑。

      系統不支援巢狀邏輯目錄。如果您為目錄提供多個對應,請以平面結構 (而非巢狀結構) 提供目錄。舉例來說,請使用 /dir1 和 /dir2,而非 /dir1 和 /dir1/dir2。

    • SFTP_PERMISSION:目錄的存取層級。如要取得唯讀存取權,請將這個值設為 READ_ONLY。如要授予讀取和寫入權限,請將這個值設為 READ_WRITE。

    注意事項:

    • 如要授予使用者多個 bucket 的存取權,請多次提供 --storage-directory-mapping 旗標,並為每個 bucket 提供目錄對應。
    • 如要為使用者設定多個公開金鑰,請在 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 使用者有權存取的 bucket 名稱,例如 example-bucket。省略 gs://。
    • (選用) BUCKET_PREFIX:要在 bucket 中設為這個目錄對應根目錄的資料夾路徑。如果省略這個值,Cloud FTP 會使用 bucket 根目錄。
    • DIRECTORY:向 SFTP 使用者顯示的邏輯登陸目錄路徑。 例如 /home/uploads。 如未指定這個值,Cloud FTP 會將到達網頁目錄設為 /。

      如果您對應多個值區或資料夾,請為每個對應提供不重複的目錄路徑。

      系統不支援巢狀邏輯目錄。如果您為目錄提供多個對應,請以平面結構 (而非巢狀結構) 提供目錄。舉例來說,請使用 /dir1 和 /dir2,而非 /dir1 和 /dir1/dir2。

    • SFTP_PERMISSION:目錄的存取層級。如要授予唯讀存取權,請將這個值設為 READ_ONLY。如要取得讀取和寫入權限,請將這個值設為 READ_WRITE。
    • SERVICE_ACCOUNT:使用者的服務帳戶。例如:username-sa@example-project.iam.gserviceaccount.com。
    • CREDENTIAL_NAME:用來識別使用者憑證的專屬名稱。
    • SSH_PUBLIC_KEY:使用者安全殼層公開金鑰的主體,採用 OpenSSH 格式。例如 ssh-rsa AAAAB3NzaC1ycRexample...。

    注意事項:

    • 如要授予使用者多個 bucket 的存取權,請在 storageDirectoryMappings 清單中提供多個 bucket 對應。
    • 如要為使用者設定多個公開金鑰,請在 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

後續步驟