更新 SFTP 使用者的安全殼層金鑰

本文說明如何更新 Cloud FTP 使用者可用於連線至 SFTP 伺服器的安全殼層 (SSH) 金鑰。

事前準備

  • 從使用者用來連線至伺服器的每個安全殼層金鑰組中,取得使用者的公開金鑰。使用者最多可有 10 個公開金鑰。

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

    產生安全殼層 (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 管理員」 (roles/ftp.admin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

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

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

更新 SFTP 使用者的安全殼層金鑰

gcloud

如要更新 SFTP 使用者的安全殼層金鑰,請執行 gcloud alpha storage ftp users update 指令。

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

  • CREDENTIAL_NAME:用來識別使用者憑證的專屬名稱。
  • SSH_PUBLIC_KEY:使用者安全殼層公開金鑰的主體,採用 OpenSSH 格式。例如 ssh-rsa AAAAB3NzaC1ycRexample...。
  • USERNAME:SFTP 使用者的使用者名稱。
  • LOCATION_ID:伺服器的位置,例如 us-west1。
  • SERVER_ID:伺服器 ID。

如要為使用者設定多個公開金鑰,請在 credentials.json 檔案中提供多個憑證。

將下列內容儲存至名為 credentials.json 的檔案:

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

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud alpha storage ftp users update USERNAME --location=LOCATION_ID \
    --server=SERVER_ID --user-credentials-from-file=credentials.json

Windows (PowerShell)

gcloud alpha storage ftp users update USERNAME --location=LOCATION_ID `
    --server=SERVER_ID --user-credentials-from-file=credentials.json

Windows (cmd.exe)

gcloud alpha storage ftp users update USERNAME --location=LOCATION_ID ^
    --server=SERVER_ID --user-credentials-from-file=credentials.json
系統會在幾秒內更新使用者。

REST

如要更新 SFTP 使用者的安全殼層金鑰,請使用 servers.users.patch 方法。在 updateMask 查詢參數中,提供 userCredentials 欄位。

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

  • PROJECT_ID:伺服器的 Google Cloud 專案 ID。
  • LOCATION_ID:伺服器的位置,例如 us-west1。
  • SERVER_ID:伺服器 ID。
  • USERNAME:SFTP 使用者的使用者名稱。
  • CREDENTIAL_NAME:用來識別使用者憑證的專屬名稱。
  • SSH_PUBLIC_KEY:使用者安全殼層公開金鑰的主體,採用 OpenSSH 格式。例如 ssh-rsa AAAAB3NzaC1ycRexample...。

如要為使用者設定多個公開金鑰,請在 userCredentials 清單中提供多個憑證。

HTTP 方法和網址:

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

JSON 要求主體:

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

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

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

用戶端程式庫

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