创建内部 SFTP 服务器

本文档介绍了如何使用 Cloud FTP 创建内部 SFTP 服务器。只能使用 Private Service Connect 在虚拟私有云 (VPC) 网络中访问内部 SFTP 服务器。网络中的员工和内部利益相关方可以使用该服务器安全地将文件传输到 Cloud Storage 以及从 Cloud Storage 传输文件。

您需要指定允许连接到服务器的项目。您可以选择指定拒绝连接的项目。

如需了解 VPC 的背景信息,请参阅 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. 收集有关服务器用户的以下信息:

    • 允许访问服务器的项目 ID 或项目编号的列表。
    • (可选)被拒绝访问服务器的项目 ID 或项目编号的列表。

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. 收集有关服务器用户的以下信息:

    • 允许访问服务器的项目 ID 或项目编号的列表。
    • (可选)被拒绝访问服务器的项目 ID 或项目编号的列表。

所需的角色

如需获得创建 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 位置。

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

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

    4. 点击继续。

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

    1. 选择内部(仅限 VPC)。

    2. 在接受的项目部分中,指定允许使用 Private Service Connect 连接到服务器的使用方项目。执行以下操作:

      1. 在项目字段中,输入允许连接的项目的项目 ID 或编号。例如 example-allowed-project。

      2. 在连接限制字段中,输入可在使用方项目中创建的 Private Service Connect 端点数上限。该值必须介于 1 到 250 个端点之间。

      3. 如需添加更多项目,请点击添加接受的项目,然后重复上述步骤。

    3. (可选)如需禁止项目连接到服务器,请在拒绝的项目部分中,点击添加拒绝的项目。输入禁止连接到服务器的使用方项目的项目 ID 或编号。

      此列表中的项目即使包含在允许的项目列表中,也会被拒绝访问服务器。

  5. 点击创建。

    服务器大约需要 10 分钟才能创建完成。

gcloud

如需创建内部服务器,请运行 gcloud alpha storage ftp servers create 命令并提供 --access-type=INTERNAL 标志。

在使用下面的命令数据之前,请先进行以下替换:

  • SERVER_ID:服务器的唯一 ID。必须以小写字母开头,并以小写字母或数字结尾。可以包含小写字母、数字和连字符。 不能以 goog 前缀开头,也不能包含字符串 google,包括近似错拼变体(如 g00gle)。长度上限为 30 个字符。
  • LOCATION_ID:服务器的Google Cloud 位置,例如 us-west1。

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

  • PROJECT_TO_ALLOW:允许使用 Private Service Connect 连接到服务器的使用方项目的项目 ID 或编号。例如 example-allowed-project。您必须至少指定一个项目。

    您最多可以允许 500 个项目。 在逗号分隔列表中提供多个项目及其各自的连接数上限。例如 --consumer-accept-list=projectA=20,projectB=15。

  • CONNECTION_LIMIT:可在使用方项目中创建的 Private Service Connect 端点数量上限。该值必须介于 1 到 250 个端点之间。
  • (可选)PROJECT_TO_REJECT:禁止连接到服务器的使用方项目的项目 ID 或编号。例如 example-rejected-project。 此列表中的项目即使包含在允许的项目列表中,也会被拒绝访问服务器。

    您最多可以拒绝 64 个项目。 在逗号分隔列表中提供多个项目。

    如果您不想明确拒绝任何项目,请省略 --consumer-reject-list 标志。

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud alpha storage ftp servers create SERVER_ID --access-type=INTERNAL \
    --location=LOCATION_ID \
    --consumer-accept-list=PROJECT_TO_ALLOW=CONNECTION_LIMIT \
    --consumer-reject-list=PROJECT_TO_REJECT

Windows (PowerShell)

gcloud alpha storage ftp servers create SERVER_ID --access-type=INTERNAL `
    --location=LOCATION_ID `
    --consumer-accept-list=PROJECT_TO_ALLOW=CONNECTION_LIMIT `
    --consumer-reject-list=PROJECT_TO_REJECT

Windows (cmd.exe)

gcloud alpha storage ftp servers create SERVER_ID --access-type=INTERNAL ^
    --location=LOCATION_ID ^
    --consumer-accept-list=PROJECT_TO_ALLOW=CONNECTION_LIMIT ^
    --consumer-reject-list=PROJECT_TO_REJECT

服务器大约需要 10 分钟才能创建完成。

REST

如需创建内部服务器,请使用 servers.create 方法并提供 internalConfig 访问配置。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:服务器的 Google Cloud 项目 ID。
  • LOCATION_ID:服务器的Google Cloud 位置,例如 us-west1。

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

  • SERVER_ID:服务器的唯一 ID。必须以小写字母开头,并以小写字母或数字结尾。可以包含小写字母、数字和连字符。 不能以 goog 前缀开头,也不能包含字符串 google,包括近似错拼变体(如 g00gle)。长度上限为 30 个字符。
  • PROJECT_TO_ALLOW:允许使用 Private Service Connect 连接到服务器的使用方项目的项目 ID 或编号。例如 example-allowed-project。您必须至少指定一个项目。

    您最多可以允许 500 个项目。

  • CONNECTION_LIMIT:可在使用方项目中创建的 Private Service Connect 端点数量上限。该值必须介于 1 到 250 个端点之间。
  • (可选)PROJECT_TO_REJECT:禁止连接到服务器的使用方项目的项目 ID 或编号。例如 example-rejected-project。 此列表中的项目即使包含在允许的项目列表中,也会被拒绝访问服务器。

    您最多可以拒绝 64 个项目。

    如果您不想明确拒绝任何项目,请省略 consumerRejectList 对象。

HTTP 方法和网址:

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

请求 JSON 正文:

{
  "accessType": "INTERNAL",
  "internalConfig": {
    "consumerAcceptList": [
      {
        "project": "projects/PROJECT_TO_ALLOW",
        "connectionLimit": CONNECTION_LIMIT
      }
    ],
    "consumerRejectList": [
      {
        "project": "projects/PROJECT_TO_REJECT"
      }
    ]
  }
}

如需发送您的请求,请展开以下选项之一:

响应会识别长时间运行的操作。

服务器大约需要 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

后续步骤