使用云助手免登录管理ECS示例

云助手命令可以在多台ECS实例中批量执行Shell、Bat或者PowerShell脚本。本文介绍如何通过Java SDK检测云助手Agent状态、运行云助手命令和查询云助手命令执行结果。

前提条件

  • 目标ECS实例已安装云助手Agent。可使用DescribeCloudAssistantStatus查看ECS实例云助手状态,若ECS未安装云助手Agent,请参见安装云助手Agent

  • 请确保代码运行环境设置了环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET。具体配置方法,请参见在Linux、macOS和Windows系统配置环境变量

  • ECS实例状态必须为运行中Running),可使用DescribeInstances获取ECS实例状态。

  • 根据ECS实例的配置,以及您需要执行的操作,准备好云助手使用的命令(Shell、Bat或者PowerShell命令)。

  • 在开发环境引入Java SDK依赖,详细配置,请参见ECS Java SDK

说明

为避免主账号泄露AccessKey带来的安全风险,建议您创建RAM用户,授予RAM用户云服务器ECS相关的访问权限,再使用RAM用户的AccessKey调用SDK。具体操作,请参见RAM用户

操作步骤

查询实例云助手Agent状态

在使用云助手执行命令管理或操作ECS实例前,建议使用DescribeCloudAssistantStatus查询实例的云助手状态。

代码示例

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.ecs20140526.AsyncClient;
import com.aliyun.sdk.service.ecs20140526.models.DescribeCloudAssistantStatusRequest;
import com.aliyun.sdk.service.ecs20140526.models.DescribeCloudAssistantStatusResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class DescribeCloudAssistantStatus {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 配置凭证信息,包括 AK、Secret 和 Token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // 确保环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET 本地环境已设置。
                .accessKeyId("ALIBABA_CLOUD_ACCESS_KEY_ID")
                .accessKeySecret("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // 使用 STS Token
                .build());
        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                // Region ID
                .region("cn-hangzhou") 
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Ecs
                                .setEndpointOverride("ecs-cn-hangzhou.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Parameter settings for API request
        DescribeCloudAssistantStatusRequest describeCloudAssistantStatusRequest = DescribeCloudAssistantStatusRequest.builder()
                .regionId("cn-hangzhou")
                .instanceId(java.util.Arrays.asList(
                        // 
                        "i-bp13orb*******"
                ))
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();
        // Asynchronously get the return value of the API request
        CompletableFuture<DescribeCloudAssistantStatusResponse> response = client.describeCloudAssistantStatus(describeCloudAssistantStatusRequest);
        // Synchronously get the return value of the API request
        DescribeCloudAssistantStatusResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        client.close();
    }
}

响应结果示例

响应结果中CloudAssistantStatus为实例内云助手运行状态,在使用云助手Agent操作ECS实例前,请确保CloudAssistantStatus状态为true

{
  "TotalCount": 1,
  "PageSize": 1,
  "RequestId": "E020564A-****************",
  "NextToken": "",
  "PageNumber": 1,
  "InstanceCloudAssistantStatusSet": {
    "InstanceCloudAssistantStatus": [
      {
        "CloudAssistantVersion": "2.2.3.612",
        "SupportSessionManager": true,
        "InstanceId": "i-bp11*************",
        "InvocationCount": 5,
        "OSType": "Linux",
        "CloudAssistantStatus": "true",
        "LastHeartbeatTime": "2024-09-10T06:42:52Z",
        "LastInvokedTime": "2024-09-10T03:22:23Z",
        "ActiveTaskCount": 0
      }
    ]
  }
}

通过云助手在实例中执行命令

使用RunCommand在一台或多台ECS实例中执行一段Shell、PowerShell或者Bat类型的脚本。

说明

执行 PowerShell 类型的命令时,您需要确保目标 ECS Windows 实例已经配置了 PowerShell 模块。

代码示例

package com.aliyun.simple;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.ecs20140526.AsyncClient;
import com.aliyun.sdk.service.ecs20140526.models.RunCommandRequest;
import com.aliyun.sdk.service.ecs20140526.models.RunCommandResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class RunCommand {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 配置凭证信息,包括 AK、Secret 和 Token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // 确保环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET 本地环境已设置。
                .accessKeyId("ALIBABA_CLOUD_ACCESS_KEY_ID")
                .accessKeySecret("ALIBABA_CLOUD_ACCESS_KEY_SECRETNDAlRU3Y8Q")
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // 使用 STS Token
                .build());
        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Ecs
                                .setEndpointOverride("ecs-cn-hangzhou.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Parameter settings for API request
        RunCommandRequest runCommandRequest = RunCommandRequest.builder()
                .regionId("cn-hangzhou")
                .type("RunShellScript")
                .commandContent("{在ESC上执行的命令内容}")
                .instanceId(java.util.Arrays.asList(
                        "i-bp11cx***********"
                ))
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();
        // Asynchronously get the return value of the API request
        CompletableFuture<RunCommandResponse> response = client.runCommand(runCommandRequest);
        // Synchronously get the return value of the API request
        RunCommandResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        client.close();
    }
}

响应结果示例

响应结果,CommandId为命令ID,InvokeId为命令执行ID。请保存此ID以用后续获取命令执行结果。

{
  "RequestId": "AC95DAC5-************************",
  "CommandId": "c-hz04*****************",
  "InvokeId": "t-hz04*************"
}

获取云助手命令执行结果

使用云助手执行Shell、PowerShell或者Bat类型脚本后,可使用InvokeIdCommandId等参数通过DescribeInvocationResults查看命令在ECS实例中的实际执行结果。

代码示例

package com.aliyun.simple;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.ecs20140526.AsyncClient;
import com.aliyun.sdk.service.ecs20140526.models.DescribeInvocationResultsRequest;
import com.aliyun.sdk.service.ecs20140526.models.DescribeInvocationResultsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class DescribeInvocationResults {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 配置凭证信息,包括 AK、Secret 和 Token
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // 确保环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET 本地环境已设置。
                .accessKeyId("ALIBABA_CLOUD_ACCESS_KEY_ID")
                .accessKeySecret("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                //.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // 使用 STS Token
                .build());
        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/Ecs
                                .setEndpointOverride("ecs-cn-hangzhou.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Parameter settings for API request
        DescribeInvocationResultsRequest describeInvocationResultsRequest = DescribeInvocationResultsRequest.builder()
                .regionId("cn-hangzhou")
                .invokeId("t-hz0**********")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();
        // Asynchronously get the return value of the API request
        CompletableFuture<DescribeInvocationResultsResponse> response = client.describeInvocationResults(describeInvocationResultsRequest);
        // Synchronously get the return value of the API request
        DescribeInvocationResultsResponse resp = response.get();
        System.out.println(new Gson().toJson(resp));
        client.close();
    }
}

响应结果示例

响应结果中InvocationStatus为实例中命令进度状态,Output为命令执行后的输出信息。

{
  "RequestId": "2D4967FE-************************",
  "Invocation": {
    "InvocationResults": {
      "InvocationResult": [
        {
          "Dropped": 2517254,
          "InvocationStatus": "Success",
          "InstanceId": "i-bp11c***********",
          "ExitCode": 0,
          "ErrorInfo": "",
          "StartTime": "2024-09-10T03:22:24Z",
          "Repeats": 1,
          "InvokeRecordStatus": "Finished",
          "FinishedTime": "2024-09-10T03:22:26Z",
          "Username": "",
          "ContainerId": "",
          "ContainerName": "",
          "Output":"{命令执行输出}",
          "Launcher": "",
          "CommandId": "c-hz04**********",
          "ErrorCode": "",
          "InvokeId": "t-hz04w**********",
          "TerminationMode": "Process",
          "Tags": {
            "Tag": []
          },
          "StopTime": ""
        }
      ]
    },
    "TotalCount": 1,
    "PageSize": 10,
    "NextToken": "",
    "PageNumber": 1
  }
}