Atualizar um servidor SFTP

Para atualizar os usuários que podem se conectar a um servidor do Cloud FTP, atualize a configuração de acesso do servidor. Também é possível atualizar metadados, como o nome de exibição do servidor.

Não é possível mudar se um servidor é externo ou interno depois que ele é criado.

Funções exigidas

Para receber a permissão necessária para atualizar um servidor SFTP, peça ao administrador para conceder a você o papel do IAM de Administrador do Cloud FTP (roles/ftp.admin) no projeto. Para mais informações sobre a concessão de papéis, consulte Gerenciar o acesso a projetos, pastas e organizações.

Esse papel predefinido contém a permissão ftp.servers.update, que é necessária para atualizar um servidor SFTP.

Também é possível receber essa permissão com papéis personalizados ou outros papéis predefinidos.

Atualizar o acesso de um servidor externo

gcloud

Para atualizar a configuração de acesso de um servidor externo, execute o comando gcloud alpha storage ftp servers update. Forneça a flag --allowed-cidr-blocks.

Antes de usar os dados do comando abaixo, faça estas substituições:

  • SERVER_ID: o ID do servidor.
  • LOCATION_ID: o local do servidor, como us-west1.
  • CIDR_BLOCK: um bloco CIDR que tem permissão para acessar o servidor. Por exemplo, 192.0.2.0/24. É necessário fornecer pelo menos um valor, e é possível fornecer no máximo 500 blocos CIDR em uma lista separada por vírgulas. Para permitir conexões de todos os endereços IP, use 0.0.0.0/0.

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud alpha storage ftp servers update SERVER_ID --location=LOCATION_ID \
    --allowed-cidr-blocks=CIDR_BLOCK

Windows (PowerShell)

gcloud alpha storage ftp servers update SERVER_ID --location=LOCATION_ID `
    --allowed-cidr-blocks=CIDR_BLOCK

Windows (cmd.exe)

gcloud alpha storage ftp servers update SERVER_ID --location=LOCATION_ID ^
    --allowed-cidr-blocks=CIDR_BLOCK
A atualização do servidor leva alguns segundos.

REST

Para atualizar a configuração de acesso de um servidor externo, use o método servers.patch. No parâmetro de consulta updateMask, forneça o campo externalConfig.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: o ID do projeto do Google Cloud do servidor.
  • LOCATION_ID: o local do servidor, como us-west1.
  • SERVER_ID: o ID do servidor.
  • CIDR_BLOCK: um bloco CIDR que tem permissão para acessar o servidor. Por exemplo, 192.0.2.0/24. É preciso fornecer pelo menos um valor, e é possível fornecer no máximo 500 blocos CIDR . Para permitir conexões de todos os endereços IP, use 0.0.0.0/0.

Método HTTP e URL:

PATCH https://ftp.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/servers/SERVER_ID?updateMask=externalConfig

Corpo JSON da solicitação:

{
  "externalConfig": {
    "allowedCidrBlocks": [
      "CIDR_BLOCK"
    ]
  }
}

Para enviar a solicitação, expanda uma destas opções:

A resposta identifica uma operação de longa duração. A atualização do servidor leva alguns segundos.

Bibliotecas de cliente

C#

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP C#.

Para se autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

using Google.Cloud.Ftp.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public sealed partial class GeneratedCloudFtpClientSnippets
{
    /// <summary>Snippet for UpdateServerAsync</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 UpdateServerAsync()
    {
        // Create client
        CloudFtpClient cloudFtpClient = await CloudFtpClient.CreateAsync();
        // Initialize request argument(s)
        Server server = new Server();
        FieldMask updateMask = new FieldMask();
        // Make the request
        Operation<Server, OperationMetadata> response = await cloudFtpClient.UpdateServerAsync(server, updateMask);

        // 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.PollOnceUpdateServerAsync(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

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP Go.

Para autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


//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.UpdateServerRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/ftp/apiv1/ftppb#UpdateServerRequest.
	}
	op, err := c.UpdateServer(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

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

Java

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP Java.

Para se autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import com.google.api.core.ApiFuture;
import com.google.cloud.ftp.v1.CloudFtpClient;
import com.google.cloud.ftp.v1.Server;
import com.google.cloud.ftp.v1.UpdateServerRequest;
import com.google.longrunning.Operation;
import com.google.protobuf.FieldMask;

public class AsyncUpdateServer {

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

  public static void asyncUpdateServer() 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()) {
      UpdateServerRequest request =
          UpdateServerRequest.newBuilder()
              .setUpdateMask(FieldMask.newBuilder().build())
              .setServer(Server.newBuilder().build())
              .setRequestId("requestId693933066")
              .build();
      ApiFuture<Operation> future = cloudFtpClient.updateServerCallable().futureCall(request);
      // Do something.
      Operation response = future.get();
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP Node.js.

Para se autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

/**
 * 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
 *  Server 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 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 callUpdateServer() {
  // Construct request
  const request = {
    server,
  };

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

callUpdateServer();

PHP

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP PHP.

Para autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Ftp\V1\Client\CloudFtpClient;
use Google\Cloud\Ftp\V1\Server;
use Google\Cloud\Ftp\V1\Server\AccessType;
use Google\Cloud\Ftp\V1\UpdateServerRequest;
use Google\Rpc\Status;

/**
 * Updates the parameters of a single Server.
 *
 * @param int $serverAccessType The access type of the Server.
 */
function update_server_sample(int $serverAccessType): void
{
    // Create a client.
    $cloudFtpClient = new CloudFtpClient();

    // Prepare the request message.
    $server = (new Server())
        ->setAccessType($serverAccessType);
    $request = (new UpdateServerRequest())
        ->setServer($server);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $cloudFtpClient->updateServer($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
{
    $serverAccessType = AccessType::ACCESS_TYPE_UNSPECIFIED;

    update_server_sample($serverAccessType);
}

Python

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP para Python.

Para se autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

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

    request = ftp_v1.UpdateServerRequest(
        server=server,
    )

    # Make the request
    operation = client.update_server(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

Ruby

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP Ruby.

Para se autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

require "google/cloud/ftp/v1"

##
# Snippet for the update_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#update_server.
#
def update_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::UpdateServerRequest.new

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

Atualizar o acesso de um servidor interno

gcloud

Para atualizar a configuração de acesso de um servidor interno, execute o comando gcloud alpha storage ftp servers update. Forneça a flag --consumer-accept-list e, se quiser, a flag --consumer-reject-list.

Antes de usar os dados do comando abaixo, faça estas substituições:

  • SERVER_ID: o ID do servidor.
  • LOCATION_ID: o local do servidor, como us-west1.
  • PROJECT_TO_ALLOW: o ID do projeto ou número de um projeto de consumidor que tem permissão para se conectar ao servidor usando o Private Service Connect. Por exemplo, example-allowed-project. É necessário especificar pelo menos um projeto.

    É possível permitir no máximo 500 projetos. Forneça vários projetos e os respectivos limites de conexão em uma lista separada por vírgulas. Por exemplo, --consumer-accept-list=projectA=20,projectB=15

  • CONNECTION_LIMIT: o número máximo de endpoints do Private Service Connect que podem ser criados no projeto do consumidor. O valor precisa ser de 1 a 250 endpoints.
  • (Opcional) PROJECT_TO_REJECT: o ID do projeto ou número de um projeto de consumidor que não pode se conectar ao servidor. Por exemplo, example-rejected-project. Os projetos nessa lista são impedidos de acessar o servidor, mesmo que estejam incluídos na lista de projetos permitidos.

    É possível rejeitar no máximo 64 projetos. Forneça vários projetos em uma lista separada por vírgulas.

    Se você não quiser rejeitar explicitamente nenhum projeto, omita a flag --consumer-reject-list.

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud alpha storage ftp servers update SERVER_ID --location=LOCATION_ID \
    --consumer-accept-list=PROJECT_TO_ALLOW=CONNECTION_LIMIT \
    --consumer-reject-list=PROJECT_TO_REJECT

Windows (PowerShell)

gcloud alpha storage ftp servers update SERVER_ID --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 update SERVER_ID --location=LOCATION_ID ^
    --consumer-accept-list=PROJECT_TO_ALLOW=CONNECTION_LIMIT ^
    --consumer-reject-list=PROJECT_TO_REJECT
Leva alguns segundos para o servidor ser atualizado.

REST

Para atualizar a configuração de acesso de um servidor interno, use o método servers.patch. No parâmetro de consulta updateMask, forneça o campo internalConfig.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: o ID do projeto Google Cloud do servidor.
  • LOCATION_ID: o local do servidor, como us-west1.
  • SERVER_ID: o ID do servidor.
  • PROJECT_TO_ALLOW: o ID do projeto ou número de um projeto consumidor que pode se conectar ao servidor usando o Private Service Connect. Por exemplo, example-allowed-project. É necessário especificar pelo menos um projeto.

    É possível permitir no máximo 500 projetos.

  • CONNECTION_LIMIT: o número máximo de endpoints do Private Service Connect que podem ser criados no projeto do consumidor. O valor precisa ser de 1 a 250 endpoints.
  • (Opcional) PROJECT_TO_REJECT: o ID do projeto ou número de um projeto de consumidor que não pode se conectar ao servidor. Por exemplo, example-rejected-project. Os projetos nessa lista são impedidos de acessar o servidor, mesmo que estejam incluídos na lista de projetos permitidos.

    É possível rejeitar no máximo 64 projetos.

    Se você não quiser rejeitar explicitamente nenhum projeto, omita o objeto consumerRejectList.

Método HTTP e URL:

PATCH https://ftp.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/servers/SERVER_ID?updateMask=internalConfig

Corpo JSON da solicitação:

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

Para enviar a solicitação, expanda uma destas opções:

A resposta identifica uma operação de longa duração. A atualização do servidor leva alguns segundos.

Bibliotecas de cliente

C#

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP C#.

Para se autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

using Google.Cloud.Ftp.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System.Threading.Tasks;

public sealed partial class GeneratedCloudFtpClientSnippets
{
    /// <summary>Snippet for UpdateServerAsync</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 UpdateServerAsync()
    {
        // Create client
        CloudFtpClient cloudFtpClient = await CloudFtpClient.CreateAsync();
        // Initialize request argument(s)
        Server server = new Server();
        FieldMask updateMask = new FieldMask();
        // Make the request
        Operation<Server, OperationMetadata> response = await cloudFtpClient.UpdateServerAsync(server, updateMask);

        // 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.PollOnceUpdateServerAsync(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

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP para Go.

Para autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


//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.UpdateServerRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/ftp/apiv1/ftppb#UpdateServerRequest.
	}
	op, err := c.UpdateServer(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

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

Java

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP Java.

Para autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import com.google.api.core.ApiFuture;
import com.google.cloud.ftp.v1.CloudFtpClient;
import com.google.cloud.ftp.v1.Server;
import com.google.cloud.ftp.v1.UpdateServerRequest;
import com.google.longrunning.Operation;
import com.google.protobuf.FieldMask;

public class AsyncUpdateServer {

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

  public static void asyncUpdateServer() 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()) {
      UpdateServerRequest request =
          UpdateServerRequest.newBuilder()
              .setUpdateMask(FieldMask.newBuilder().build())
              .setServer(Server.newBuilder().build())
              .setRequestId("requestId693933066")
              .build();
      ApiFuture<Operation> future = cloudFtpClient.updateServerCallable().futureCall(request);
      // Do something.
      Operation response = future.get();
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP Node.js.

Para se autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

/**
 * 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
 *  Server 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 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 callUpdateServer() {
  // Construct request
  const request = {
    server,
  };

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

callUpdateServer();

PHP

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP PHP.

Para autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Ftp\V1\Client\CloudFtpClient;
use Google\Cloud\Ftp\V1\Server;
use Google\Cloud\Ftp\V1\Server\AccessType;
use Google\Cloud\Ftp\V1\UpdateServerRequest;
use Google\Rpc\Status;

/**
 * Updates the parameters of a single Server.
 *
 * @param int $serverAccessType The access type of the Server.
 */
function update_server_sample(int $serverAccessType): void
{
    // Create a client.
    $cloudFtpClient = new CloudFtpClient();

    // Prepare the request message.
    $server = (new Server())
        ->setAccessType($serverAccessType);
    $request = (new UpdateServerRequest())
        ->setServer($server);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $cloudFtpClient->updateServer($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
{
    $serverAccessType = AccessType::ACCESS_TYPE_UNSPECIFIED;

    update_server_sample($serverAccessType);
}

Python

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP Python.

Para autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

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

    request = ftp_v1.UpdateServerRequest(
        server=server,
    )

    # Make the request
    operation = client.update_server(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

Ruby

Para saber como instalar e usar a biblioteca de cliente do Cloud FTP, consulte Bibliotecas de cliente do Cloud FTP. Para mais informações, consulte a documentação de referência da API Cloud FTP Ruby.

Para se autenticar no Cloud FTP, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

require "google/cloud/ftp/v1"

##
# Snippet for the update_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#update_server.
#
def update_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::UpdateServerRequest.new

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

Atualizar o nome de exibição de um servidor

gcloud

Para atualizar metadados, como o nome de exibição de um servidor SFTP, execute o comando gcloud alpha storage ftp servers update.

Antes de usar os dados do comando abaixo, faça estas substituições:

  • SERVER_ID: o ID do servidor.
  • LOCATION_ID: o local do servidor, como us-west1.
  • DISPLAY_NAME: um nome de exibição para o servidor.

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud alpha storage ftp servers update SERVER_ID --location=LOCATION_ID \
    --display-name="DISPLAY_NAME"

Windows (PowerShell)

gcloud alpha storage ftp servers update SERVER_ID --location=LOCATION_ID `
    --display-name="DISPLAY_NAME"

Windows (cmd.exe)

gcloud alpha storage ftp servers update SERVER_ID --location=LOCATION_ID ^
    --display-name="DISPLAY_NAME"
A atualização do servidor leva alguns segundos.

REST

Para atualizar metadados, como o nome de exibição de um servidor SFTP, use o método servers.patch. No parâmetro de consulta updateMask, forneça uma lista separada por vírgulas de campos a serem atualizados. No corpo da solicitação, forneça um objeto JSON com os valores a serem definidos.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • PROJECT_ID: o ID do projeto Google Cloud do servidor.
  • LOCATION_ID: o local do servidor, como us-west1.
  • SERVER_ID: o ID do servidor.
  • FIELDS_TO_UPDATE: uma lista separada por vírgulas de campos a serem atualizados, em relação ao recurso do servidor. Por exemplo, para atualizar o nome de exibição, forneça o parâmetro de consulta updateMask=displayName.
  • DISPLAY_NAME: um nome de exibição para o servidor.

Método HTTP e URL:

PATCH https://ftp.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/servers/SERVER_ID?updateMask=FIELDS_TO_UPDATE

Corpo JSON da solicitação:

{
  "displayName": "DISPLAY_NAME"
}

Para enviar a solicitação, expanda uma destas opções:

A resposta identifica uma operação de longa duração. A atualização do servidor leva alguns segundos.