從 SFTP 伺服器刪除使用者

本文說明如何從 Cloud FTP 伺服器移除使用者。

必要的角色

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

這個預先定義的角色具備 ftp.users.delete 權限,可刪除 SFTP 使用者。

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

刪除 SFTP 使用者

gcloud

  1. 刪除代表使用者存取 Cloud Storage 資源的服務帳戶:

    1. 取得使用者服務帳戶的電子郵件地址。例如:USERNAME-sa@PROJECT_ID.。如需相關步驟,請參閱「取得使用者詳細資料」。

    2. 刪除服務帳戶:

      gcloud iam service-accounts delete SERVICE_ACCOUNT

      將 SERVICE_ACCOUNT 替換為服務帳戶的電子郵件地址。

  2. 如要從 SFTP 伺服器刪除使用者,請執行 gcloud alpha storage ftp users delete 指令。

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

    • USERNAME:SFTP 使用者的使用者名稱。
    • LOCATION_ID:伺服器的位置,例如 us-west1。
    • SERVER_ID:伺服器 ID。

    執行下列指令:

    Linux、macOS 或 Cloud Shell

    gcloud alpha storage ftp users delete USERNAME --location=LOCATION_ID \
        --server=SERVER_ID

    Windows (PowerShell)

    gcloud alpha storage ftp users delete USERNAME --location=LOCATION_ID `
        --server=SERVER_ID

    Windows (cmd.exe)

    gcloud alpha storage ftp users delete USERNAME --location=LOCATION_ID ^
        --server=SERVER_ID
    系統需要幾秒鐘才能刪除使用者。

REST

  1. 刪除代表使用者存取 Cloud Storage 資源的服務帳戶:

    1. 取得使用者服務帳戶的電子郵件地址。例如:USERNAME-sa@PROJECT_ID.。如需相關步驟,請參閱「取得使用者詳細資料」。

    2. 刪除服務帳戶:

      gcloud iam service-accounts delete SERVICE_ACCOUNT

      將 SERVICE_ACCOUNT 替換成服務帳戶的電子郵件地址。

  2. 如要從 SFTP 伺服器刪除使用者,請使用 servers.users.delete 方法。

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

    • PROJECT_ID: Google Cloud 專案 ID。
    • LOCATION_ID:伺服器的位置,例如 us-west1。
    • SERVER_ID:伺服器 ID。
    • USERNAME:SFTP 使用者的使用者名稱。

    HTTP 方法和網址:

    DELETE https://ftp.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/servers/SERVER_ID/users/USERNAME

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

    回應會識別長時間執行的作業。 系統會在幾秒內刪除使用者。 <0

用戶端程式庫

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 DeleteUserAsync</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 DeleteUserAsync()
    {
        // Create client
        CloudFtpClient cloudFtpClient = await CloudFtpClient.CreateAsync();
        // Initialize request argument(s)
        string name = "projects/[PROJECT]/locations/[LOCATION]/servers/[SERVER]/users/[USER]";
        // Make the request
        Operation<Empty, OperationMetadata> response = await cloudFtpClient.DeleteUserAsync(name);

        // Poll until the returned long-running operation is complete
        Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
        // Retrieve the operation result
        Empty 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<Empty, OperationMetadata> retrievedResponse = await cloudFtpClient.PollOnceDeleteUserAsync(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            Empty 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.DeleteUserRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/ftp/apiv1/ftppb#DeleteUserRequest.
	}
	op, err := c.DeleteUser(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

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

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.DeleteUserRequest;
import com.google.cloud.ftp.v1.UserName;
import com.google.longrunning.Operation;

public class AsyncDeleteUser {

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

  public static void asyncDeleteUser() 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()) {
      DeleteUserRequest request =
          DeleteUserRequest.newBuilder()
              .setName(UserName.of("[PROJECT]", "[LOCATION]", "[SERVER]", "[USER]").toString())
              .setForce(true)
              .build();
      ApiFuture<Operation> future = cloudFtpClient.deleteUserCallable().futureCall(request);
      // Do something.
      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. Name of the resource
 */
// const name = 'abc123'
/**
 *  Optional. If set to true, the request will force the deletion of the User.
 */
// const force = true

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

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

async function callDeleteUser() {
  // Construct request
  const request = {
    name,
  };

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

callDeleteUser();

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\DeleteUserRequest;
use Google\Rpc\Status;

/**
 * Deletes a single User.
 *
 * @param string $formattedName Name of the resource
 *                              Please see {@see CloudFtpClient::userName()} for help formatting this field.
 */
function delete_user_sample(string $formattedName): void
{
    // Create a client.
    $cloudFtpClient = new CloudFtpClient();

    // Prepare the request message.
    $request = (new DeleteUserRequest())
        ->setName($formattedName);

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

        if ($response->operationSucceeded()) {
            printf('Operation completed successfully.' . PHP_EOL);
        } 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
{
    $formattedName = CloudFtpClient::userName('[PROJECT]', '[LOCATION]', '[SERVER]', '[USER]');

    delete_user_sample($formattedName);
}

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_delete_user():
    # Create a client
    client = ftp_v1.CloudFtpClient()

    # Initialize request argument(s)
    request = ftp_v1.DeleteUserRequest(
        name="name_value",
    )

    # Make the request
    operation = client.delete_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 delete_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#delete_user.
#
def delete_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::DeleteUserRequest.new

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

後續步驟