创建外部 SFTP 服务器

本文档介绍了如何使用 Cloud FTP 创建外部 SFTP 服务器。外部 SFTP 服务器可通过互联网访问。 网络外部的合作伙伴可以使用该服务器安全地将文件传输到 Cloud Storage 和从 Cloud Storage 传输文件。

您可以根据用户的 IP 地址限制对外部 SFTP 服务器的访问权限。

如需了解创建只能在您的 虚拟私有云 (VPC) 网络中访问的内部服务器的步骤,请参阅 创建内部 SFTP 服务器。 创建服务器后,您无法更改服务器是外部服务器还是内部服务器。

准备工作

控制台

  1. 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

  2. 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.

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

  4. 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

  5. 如果您想根据用户的 IP 地址限制对服务器的访问权限,请收集允许访问服务器的 CIDR 块列表。

gcloud

  1. 安装 Google Cloud CLI。

  2. 配置 gcloud CLI 以使用您的联合身份。

    如需了解详情,请参阅 使用联合身份登录 gcloud CLI。

  3. 如需初始化 gcloud CLI,请运行以下命令:

    gcloud init
  4. 创建或选择 Google Cloud 项目。

    选择或创建项目所需角色

    • 选择项目:选择项目不需要特定的 IAM 角色,您可以选择已被授予角色的任何项目。
    • 创建项目:如需创建项目,您需要 Project Creator 角色 (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 项目名称。

  5. 如果您要使用现有项目来完成本指南, 请验证您是否拥有完成本指南所需的权限。如果您创建了新项目, 则您已拥有所需的权限。

  6. 验证您的 Google Cloud 项目是否已启用结算功能。

  7. 启用 Cloud FTP API(如果尚未启用):

    启用 API 所需的角色

    如需启用 API,您需要拥有 serviceusage.services.enable 权限。如果您 创建了项目,则您可能已通过 Owner 角色 (roles/owner) 拥有此权限。否则,您可以通过 Service Usage Admin 角色 (roles/serviceusage.serviceUsageAdmin) 获得此权限。 了解如何授予角色。

    gcloud services enable ftp.googleapis.com
  8. 如果您想根据用户的 IP 地址限制对服务器的访问权限,请收集允许访问服务器的 CIDR 块列表。

所需角色

如需获得创建 SFTP 服务器所需的权限,请让您的管理员为您授予项目的Cloud FTP Admin (roles/ftp.admin) IAM 角色。如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。

此预定义角色包含创建 SFTP 服务器所需的 ftp.servers.create 权限。

您也可以使用自定义角色或其他预定义角色来获取此权限。

创建外部服务器

控制台

  1. 在 Google Cloud 控制台中,前往 Cloud FTP 页面。

    前往 Cloud FTP

  2. 点击创建服务器 。

  3. 在服务器配置 标签页上,输入服务器的基本详细信息:

    1. 在服务器 ID 字段中,输入服务器的唯一 ID。

    2. 在区域 列表中,选择 Google Cloud 位置 for 服务器。

      为获得最快的数据传输速度,请在存储数据的 Cloud Storage 存储桶所在的同一位置创建服务器。 如果 Cloud FTP 不支持存储桶的位置,请选择最近的可用位置。

    3. (可选)输入服务器的显示名称。

    4. 点击继续 。

  4. 在网络和安全 标签页上,配置服务器的连接性:

    1. 选择外部(公共 IP) 。

    2. 在允许的 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 存储桶所在的同一位置创建服务器。如果 Cloud FTP 不支持存储桶的位置,请选择最近的可用位置。

  • 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 存储桶所在的同一位置创建服务器。如果 Cloud FTP 不支持存储桶的位置,请选择最近的可用位置。

  • 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

后续步骤