全部產品
Search
文件中心

Elastic Compute Service:使用雲助手免登入管理ECS樣本

更新時間:Nov 22, 2024

雲助手命令可以在多台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使用者Elastic Compute Service相關的存取權限,再使用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
  }
}