如何通过 Java SDK 使用 AWS 端口转发会话

How to use an AWS Port Forwarding session via Java SDK

我正在使用 AWSSimpleSystemsManagementAsync 启动会话,如下所示:

Map<String, List<String>> parameters = new HashMap<>();
parameters.put("portNumber", Arrays.asList("80"));
parameters.put("localPortNumber", Arrays.asList("8080"));

StartSessionResult result =
    getSsmClient()
        .startSession(
            new StartSessionRequest()
                .withTarget(sb.toString())
                .withDocumentName("AWS-StartPortForwardingSession")
                .withParameters(parameters));

sessionId = result.getSessionId();

这似乎有效并模仿了我可以手动执行的操作:

aws ssm start-session --target "Your Instance ID" --document-name AWS-StartPortForwardingSession --parameters "portNumber"=["80"],"localPortNumber"=["8080"]

当我手动 运行 时,我会在 localhost:8080 打开我的浏览器,以便根据需要与我的应用程序进行交互,但我很难通过 SDK 做这种事情,因为打开启动会话后浏览器似乎无法正常工作。

希望我只是遗漏了一些东西。

假设您已经按照 https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html

安装了会话管理器插件

下一步将通过像这样生成一个新的会话管理器插件进程将其附加到您新创建的会话。

...
StartSessionResult result = ssmClient.startSession(ssRequest);

StringBuilder responseJson = new StringBuilder("{");
responseJson.append("\"SessionId\":");
responseJson.append("\"");
responseJson.append(result.getSessionId());
responseJson.append("\"");
responseJson.append(",\"TokenValue\":");
responseJson.append("\"");
responseJson.append(result.getTokenValue());
responseJson.append("\"");
responseJson.append(",\"StreamUrl\":");
responseJson.append("\"");
responseJson.append(result.getStreamUrl());
responseJson.append("\"");
responseJson.append("}");

List<String> arguments = new ArrayList<>();
arguments.add("session-manager-plugin");
arguments.add(responseJson.toString());
arguments.add(AWS_REGION); // Whatever region you use
arguments.add("StartSession");
arguments.add(AWS_PROFILE_NAME); // Whatever profile you use
arguments.add("{\"Target\":\"i-xxxx\",\"DocumentName\":\"AWS-StartPortForwardingSession\",\"Parameters\":{\"portNumber\":[\"xx\"],\"localPortNumber\":[\"yyyy\"]}}");
arguments.add("https://ssm.us-east-1.amazonaws.com/"); // SSM regional endpoint

try {
    ProcessBuilder pb = new ProcessBuilder(arguments.toArray(new String[] {}));
    pb.redirectErrorStream(true);
    Process p = pb.start();
    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while (true) {
        line = r.readLine();
        if (line == null) { break; }
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

该片段应在您的控制台中产生以下内容

Starting session with SessionId: aws-sdk-java-zzzz
Port yyyy opened for sessionId aws-sdk-java-zzzz.