更新 SFTP 使用者的服務帳戶

本文說明如何更新 Cloud FTP 使用者的服務帳戶。服務帳戶會代表使用者存取 Cloud Storage 資源。

大致來說,更新使用者服務帳戶的步驟如下:

  1. 設定服務帳戶並授予適當的 IAM 角色。
  2. 更新附加至使用者的服務帳戶。

建議您為每位使用者使用專屬服務帳戶,以便分別管理每位使用者的 SFTP 存取權。

必要的角色

如要取得更新 SFTP 使用者所需的權限,請要求管理員授予您專案的「FTP 管理員」 (roles/ftp.admin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

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

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

設定服務帳戶

  1. 如果使用者還沒有服務帳戶,請建立服務帳戶。

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

    將 USERNAME 替換為 SFTP 使用者的專屬使用者名稱。使用者名稱開頭須為小寫英文字母,可包含小寫英文字母、數字或連字號。

    如果成功,系統會顯示類似 Created service account [example-userid-sa] 的訊息。

  2. 將服務帳戶使用者 (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
    
  3. 將存取儲存空間所需的 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 角色。

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

  4. 授權 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 替換為服務代理的電子郵件地址。

接著,更新使用者的服務帳戶。

更新使用者的服務帳戶

gcloud

如要更新附加至 SFTP 使用者的服務帳戶,請執行 gcloud alpha storage ftp users update 指令。

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

  • USERNAME:SFTP 使用者的使用者名稱。
  • LOCATION_ID:伺服器的位置,例如 us-west1。
  • SERVER_ID:伺服器 ID。
  • SERVICE_ACCOUNT:使用者的服務帳戶。例如:username-sa@example-project.iam.gserviceaccount.com。

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud alpha storage ftp users update USERNAME --location=LOCATION_ID \
    --server=SERVER_ID --customer-service-account=SERVICE_ACCOUNT

Windows (PowerShell)

gcloud alpha storage ftp users update USERNAME --location=LOCATION_ID `
    --server=SERVER_ID --customer-service-account=SERVICE_ACCOUNT

Windows (cmd.exe)

gcloud alpha storage ftp users update USERNAME --location=LOCATION_ID ^
    --server=SERVER_ID --customer-service-account=SERVICE_ACCOUNT
系統會在幾秒內更新使用者。

REST

如要更新附加至 SFTP 使用者的服務帳戶,請使用 servers.users.patch 方法。在 updateMask 查詢參數中,提供 customerServiceAccount 欄位。

使用任何要求資料之前,請先修改下列項目的值:

  • PROJECT_ID:伺服器的 Google Cloud 專案 ID。
  • LOCATION_ID:伺服器的位置,例如 us-west1。
  • SERVER_ID:伺服器 ID。
  • USERNAME:SFTP 使用者的使用者名稱。
  • SERVICE_ACCOUNT:使用者的服務帳戶。例如:username-sa@example-project.iam.gserviceaccount.com。

HTTP 方法和網址:

PATCH https://ftp.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/servers/SERVER_ID/users/USERNAME?updateMask=customerServiceAccount

JSON 要求主體:

{
  "customerServiceAccount": "SERVICE_ACCOUNT"
}

請展開以下其中一個選項,以傳送要求:

回應會指出長時間執行的作業。 系統會在幾秒內更新使用者。

用戶端程式庫

C#

如要瞭解如何安裝及使用 Cloud FTP 的用戶端程式庫,請參閱「Cloud FTP 用戶端程式庫」。詳情請參閱「Cloud FTP C# API 參考文件」。

如要向 Cloud FTP 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證機制」。

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

public sealed partial class GeneratedCloudFtpClientSnippets
{
    /// <summary>Snippet for UpdateUserAsync</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 UpdateUserAsync()
    {
        // Create client
        CloudFtpClient cloudFtpClient = await CloudFtpClient.CreateAsync();
        // Initialize request argument(s)
        User user = new User();
        FieldMask updateMask = new FieldMask();
        // Make the request
        Operation<User, OperationMetadata> response = await cloudFtpClient.UpdateUserAsync(user, updateMask);

        // 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.PollOnceUpdateUserAsync(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.UpdateUserRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/ftp/apiv1/ftppb#UpdateUserRequest.
	}
	op, err := c.UpdateUser(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.UpdateUserRequest;
import com.google.cloud.ftp.v1.User;
import com.google.longrunning.Operation;
import com.google.protobuf.FieldMask;

public class AsyncUpdateUser {

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

  public static void asyncUpdateUser() 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()) {
      UpdateUserRequest request =
          UpdateUserRequest.newBuilder()
              .setUpdateMask(FieldMask.newBuilder().build())
              .setUser(User.newBuilder().build())
              .build();
      ApiFuture<Operation> future = cloudFtpClient.updateUserCallable().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.
 */
/**
 *  Optional. Field mask is used to specify the fields to be overwritten in the
 *  User resource by the update.
 *  The fields specified in the update_mask are relative to the resource, not
 *  the full request. A field will be overwritten if it is in the mask. If the
 *  user does not provide a mask then all fields present in the request will be
 *  overwritten.
 */
// const updateMask = {}
/**
 *  Required. The resource being updated
 */
// const user = {}

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

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

async function callUpdateUser() {
  // Construct request
  const request = {
    user,
  };

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

callUpdateUser();

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\StorageDirectoryMapping;
use Google\Cloud\Ftp\V1\StorageDirectoryMapping\Permission;
use Google\Cloud\Ftp\V1\UpdateUserRequest;
use Google\Cloud\Ftp\V1\User;
use Google\Cloud\Ftp\V1\UserCredential;
use Google\Cloud\Ftp\V1\UserCredential\Type;
use Google\Rpc\Status;

/**
 * Updates the parameters of a single User.
 *
 * @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 update_user_sample(
    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 UpdateUserRequest())
        ->setUser($user);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $cloudFtpClient->updateUser($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
{
    $userCustomerServiceAccount = '[CUSTOMER_SERVICE_ACCOUNT]';
    $userUserCredentialsCredentialName = '[CREDENTIAL_NAME]';
    $userUserCredentialsCredentialType = Type::TYPE_UNSPECIFIED;
    $userStorageDirectoryMappingsBucket = '[BUCKET]';
    $userStorageDirectoryMappingsDirectory = '[DIRECTORY]';
    $userStorageDirectoryMappingsPermission = Permission::PERMISSION_UNSPECIFIED;

    update_user_sample(
        $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_update_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.UpdateUserRequest(
        user=user,
    )

    # Make the request
    operation = client.update_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 update_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#update_user.
#
def update_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::UpdateUserRequest.new

  # Call the update_user method.
  result = client.update_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

後續步驟