建立外部 SFTP 伺服器

本文說明如何使用 Cloud FTP 建立外部 SFTP 伺服器。外部 SFTP 伺服器可透過網際網路存取。網路外部的合作夥伴可以使用伺服器,安全地在 Cloud Storage 之間傳輸檔案。

您可以根據使用者的 IP 位址,限制外部 SFTP 伺服器的存取權。

如要建立只能在虛擬私有雲 (VPC) 網路中存取的內部伺服器,請參閱「建立內部 SFTP 伺服器」一文。伺服器建立後,就無法變更伺服器是外部或內部。

事前準備

控制台

  1. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎 建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  4. Verify that billing is enabled for your Google Cloud project.

  5. Enable the Cloud FTP API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  6. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  7. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  8. Verify that billing is enabled for your Google Cloud project.

  9. Enable the Cloud FTP API, if it is not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  10. 如要根據使用者的 IP 位址限制伺服器存取權,請收集允許存取伺服器的 CIDR 區塊清單。

gcloud

  1. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎 建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
  2. 安裝 Google Cloud CLI。

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

  4. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  5. 建立或選取 Google Cloud 專案。

    選取或建立專案所需的角色

    • 選取專案:選取專案時不需要特定 IAM 角色,只要您獲派某個專案的角色,即可選取該專案。
    • 建立專案:如要建立專案,您必須具備專案建立者角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色。
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      將 PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      將 PROJECT_ID 替換為 Google Cloud 專案名稱。

  6. 如要使用現有專案進行本指南中的操作,請確認您具有完成本指南所需的權限。如果您建立新專案,則已具備必要權限。

  7. 確認 Google Cloud 專案已啟用計費功能。

  8. 啟用 Cloud FTP API (如果尚未啟用):

    啟用 API 所需的角色

    您必須具備 serviceusage.services.enable 權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「Service Usage 管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    gcloud services enable ftp.googleapis.com
  9. 安裝 Google Cloud CLI。

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

  11. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  12. 建立或選取 Google Cloud 專案。

    選取或建立專案所需的角色

    • 選取專案:選取專案時不需要特定 IAM 角色,只要您獲派某個專案的角色,即可選取該專案。
    • 建立專案:如要建立專案,您必須具備專案建立者角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色。
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      將 PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      將 PROJECT_ID 替換為 Google Cloud 專案名稱。

  13. 如要使用現有專案進行本指南中的操作,請確認您具有完成本指南所需的權限。如果您建立新專案,則已具備必要權限。

  14. 確認 Google Cloud 專案已啟用計費功能。

  15. 啟用 Cloud FTP API (如果尚未啟用):

    啟用 API 所需的角色

    您必須具備 serviceusage.services.enable 權限,才能啟用 API。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「Service Usage 管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。

    gcloud services enable ftp.googleapis.com
  16. 如要根據使用者的 IP 位址限制伺服器存取權,請收集允許存取伺服器的 CIDR 區塊清單。

必要的角色

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

這個預先定義的角色具備建立 SFTP 伺服器所需的權限。如要查看確切的必要權限,請展開「Required permissions」(必要權限) 部分:

所需權限

必須具備下列權限,才能建立 SFTP 伺服器:

  • ftp.servers.create
  • 如要使用 Google Cloud 控制台執行這項工作:
    • ftp.servers.list
    • ftp.locations.list

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

建立外部伺服器

控制台

  1. 前往 Google Cloud 控制台的「Cloud FTP」頁面。

    前往 Cloud FTP

  2. 按一下「建立伺服器」。

  3. 在「Server configuration」(伺服器設定) 分頁中,輸入伺服器的基本詳細資料:

    1. 在「Server ID」(伺服器 ID) 欄位中,輸入伺服器的專屬 ID。

    2. 在「Region」(區域) 清單中,選取伺服器的Google Cloud 位置。

      為達到最快的資料移轉速度,請在儲存資料的 Cloud Storage bucket 所在位置建立伺服器。如果 Cloud FTP 不支援 bucket 的位置,請選取最接近的可用位置。

    3. (選用) 輸入伺服器的顯示名稱。

    4. 按一下「繼續」。

  4. 在「Networking and security」(網路和安全性) 分頁中,設定伺服器的連線能力:

    1. 選取「外部 (公開 IP)」。

    2. 在「Allowed IP ranges」(允許的 IP 範圍) 欄位中,提供允許存取伺服器的 CIDR 區塊,然後按下 Enter 鍵。例如 192.0.2.0/24。您至少須提供一個值,最多可提供 500 個 CIDR 區塊。如要允許所有 IP 位址連線,請使用 0.0.0.0/0。

  5. 點選「建立」。

    伺服器建立作業約需 10 分鐘。

gcloud

如要建立外部伺服器,請執行 gcloud alpha storage ftp servers create 指令,並提供 --access-type=EXTERNAL 旗標。

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

  • SERVER_ID:伺服器的專屬 ID。開頭須為小寫英文字母,結尾須為小寫英文字母或數字。可使用小寫英文字母、數字和連字號。 開頭不得為前置字串 goog,也不得包含字串 google,包括 g00gle 等近似拼寫錯誤。長度上限為 30 個半形字元。
  • LOCATION_ID:伺服器的Google Cloud 位置,例如 us-west1。

    為確保資料移轉速度最快,請在儲存資料的 Cloud Storage bucket 所在位置建立伺服器。如果 Cloud FTP 不支援 bucket 的位置,請選取最接近的可用位置。

  • CIDR_BLOCK:允許存取伺服器的 CIDR 區塊。例如:192.0.2.0/24。您至少須提供一個值,最多可提供 500 個 CIDR 區塊,並以逗號分隔的清單提供。如要允許所有 IP 位址連線,請使用 0.0.0.0/0。

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud alpha storage ftp servers create SERVER_ID --access-type=EXTERNAL \
    --location=LOCATION_ID --allowed-cidr-blocks=CIDR_BLOCK

Windows (PowerShell)

gcloud alpha storage ftp servers create SERVER_ID --access-type=EXTERNAL `
    --location=LOCATION_ID --allowed-cidr-blocks=CIDR_BLOCK

Windows (cmd.exe)

gcloud alpha storage ftp servers create SERVER_ID --access-type=EXTERNAL ^
    --location=LOCATION_ID --allowed-cidr-blocks=CIDR_BLOCK

伺服器建立作業約需 10 分鐘。

REST

如要建立外部伺服器,請使用 servers.create 方法,並提供 externalConfig 存取權設定。

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

  • PROJECT_ID:伺服器的 Google Cloud 專案 ID。
  • LOCATION_ID:伺服器的Google Cloud 位置,例如 us-west1。

    為確保資料移轉速度最快,請在儲存資料的 Cloud Storage bucket 所在位置建立伺服器。如果 Cloud FTP 不支援 bucket 的位置,請選取最接近的可用位置。

  • SERVER_ID:伺服器的專屬 ID。開頭須為小寫英文字母,結尾須為小寫英文字母或數字。可使用小寫英文字母、數字和連字號。 開頭不得為前置字串 goog,也不得包含字串 google,包括 g00gle 等近似拼寫錯誤。長度上限為 30 個半形字元。
  • CIDR_BLOCK:允許存取伺服器的 CIDR 區塊。例如:192.0.2.0/24。您至少須提供一個值,最多可提供 500 個 CIDR 區塊。如要允許所有 IP 位址連線,請使用 0.0.0.0/0。

HTTP 方法和網址:

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

JSON 要求主體:

{
  "accessType": "EXTERNAL",
  "externalConfig": {
    "allowedCidrBlocks": [
      "CIDR_BLOCK"
      ]
  }
}

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

回應會指出長時間執行的作業。

伺服器建立作業約需 10 分鐘。

用戶端程式庫

如要建立外部伺服器,請將存取權類型設為外部,並提供外部存取權設定。

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 CreateServerAsync</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 CreateServerAsync()
    {
        // Create client
        CloudFtpClient cloudFtpClient = await CloudFtpClient.CreateAsync();
        // Initialize request argument(s)
        string parent = "projects/[PROJECT]/locations/[LOCATION]";
        Server server = new Server();
        string serverId = "";
        // Make the request
        Operation<Server, OperationMetadata> response = await cloudFtpClient.CreateServerAsync(parent, server, serverId);

        // Poll until the returned long-running operation is complete
        Operation<Server, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
        // Retrieve the operation result
        Server 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<Server, OperationMetadata> retrievedResponse = await cloudFtpClient.PollOnceCreateServerAsync(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            Server 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.CreateServerRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/ftp/apiv1/ftppb#CreateServerRequest.
	}
	op, err := c.CreateServer(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.CreateServerRequest;
import com.google.cloud.ftp.v1.LocationName;
import com.google.cloud.ftp.v1.Server;
import com.google.longrunning.Operation;

public class AsyncCreateServer {

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

  public static void asyncCreateServer() 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()) {
      CreateServerRequest request =
          CreateServerRequest.newBuilder()
              .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
              .setServerId("serverId1379103678")
              .setServer(Server.newBuilder().build())
              .setRequestId("requestId693933066")
              .build();
      ApiFuture<Operation> future = cloudFtpClient.createServerCallable().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 ID for the server. Must start with a lowercase letter,
 *  and end with a lowercase letter or number. Can contain lowercase letters,
 *  numbers, and hyphens. Maximum length is 30 characters.
 */
// const serverId = 'abc123'
/**
 *  Required. The resource being created
 */
// const server = {}
/**
 *  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 callCreateServer() {
  // Construct request
  const request = {
    parent,
    serverId,
    server,
  };

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

callCreateServer();

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\CreateServerRequest;
use Google\Cloud\Ftp\V1\Server;
use Google\Cloud\Ftp\V1\Server\AccessType;
use Google\Rpc\Status;

/**
 * Creates a new Server in a given project and location.
 *
 * @param string $formattedParent  Value for parent. Please see
 *                                 {@see CloudFtpClient::locationName()} for help formatting this field.
 * @param string $serverId         A unique ID for the server. Must start with a lowercase letter,
 *                                 and end with a lowercase letter or number. Can contain lowercase letters,
 *                                 numbers, and hyphens. Maximum length is 30 characters.
 * @param int    $serverAccessType The access type of the Server.
 */
function create_server_sample(
    string $formattedParent,
    string $serverId,
    int $serverAccessType
): void {
    // Create a client.
    $cloudFtpClient = new CloudFtpClient();

    // Prepare the request message.
    $server = (new Server())
        ->setAccessType($serverAccessType);
    $request = (new CreateServerRequest())
        ->setParent($formattedParent)
        ->setServerId($serverId)
        ->setServer($server);

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

        if ($response->operationSucceeded()) {
            /** @var Server $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::locationName('[PROJECT]', '[LOCATION]');
    $serverId = '[SERVER_ID]';
    $serverAccessType = AccessType::ACCESS_TYPE_UNSPECIFIED;

    create_server_sample($formattedParent, $serverId, $serverAccessType);
}

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

    # Initialize request argument(s)
    server = ftp_v1.Server()
    server.access_type = "INTERNAL"

    request = ftp_v1.CreateServerRequest(
        parent="parent_value",
        server_id="server_id_value",
        server=server,
    )

    # Make the request
    operation = client.create_server(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_server 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_server.
#
def create_server
  # 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::CreateServerRequest.new

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

後續步驟