SFTP 사용자의 SSH 키 업데이트

이 문서에서는 Cloud FTP 사용자가 SFTP 서버에 연결하는 데 사용할 수 있는 시큐어 셸 (SSH) 키를 업데이트하는 방법을 보여줍니다.

시작하기 전에

  • 서버에 연결하는 데 사용할 각 SSH 키 쌍에서 사용자의 공개 키를 가져옵니다. 사용자는 최대 10개의 공개 키를 보유할 수 있습니다.

    사용자에게 SSH 키 쌍이 없는 경우 다음 단계에 따라 키 쌍을 생성합니다.

    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 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

이 사전 정의된 역할에는 SFTP 사용자를 업데이트하는 데 필요한 ftp.users.update 권한이 포함되어 있습니다.

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한 을 부여받을 수도 있습니다.

SFTP 사용자의 SSH 키 업데이트

gcloud

SFTP 사용자의 SSH 키를 업데이트하려면 gcloud alpha storage ftp users update 명령어를 실행합니다.

아래의 명령어 데이터를 사용하기 전에, 다음을 바꿉니다.

  • CREDENTIAL_NAME: 사용자 인증 정보를 식별하는 고유한 이름입니다.
  • SSH_PUBLIC_KEY: OpenSSH 형식의 사용자 SSH 공개 키 본문입니다. 예를 들면 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 사용자의 SSH 키를 업데이트하려면 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 공개 키 본문입니다. 예를 들면 ssh-rsa AAAAB3NzaC1ycRexample...입니다.

사용자의 공개 키를 여러 개 구성하려면 userCredentials 목록에 여러 인증 정보를 제공합니다.

HTTP 메서드 및 URL:

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