gpt4 book ai didi

amazon-web-services - AWS Java SDK - 在 EC2 实例上使用 SSM 运行命令

转载 作者:行者123 更新时间:2023-12-04 12:25:06 27 4
gpt4 key购买 nike

我在网上找不到任何示例,也找不到解释如何执行此操作的文档。基本上我有一个列表 视窗 EC2 实例和我需要运行 quser命令中的每一个来检查有多少用户登录。

可以使用 来做到这一点。 AWS 系统管理器 服务并运行 AWS-RunPowerShellScript 命令。我只找到了使用 的示例AWS CLI ,像这样:

aws ssm send-command --instance-ids "instance ID" --document-name "AWS-RunPowerShellScript" --comment "Get Users" --parameters commands=quser --output text

但是如何使用 AWS Java SDK 1.11.x 完成此操作?

最佳答案

@Alexandre Krabbe 你问这个问题已经一年多了。所以不确定答案会帮助你。但我最近也在尝试做同样的事情,这让我想到了这个悬而未决的问题。我最终解决了这个问题,并认为我的回答可以帮助其他面临同样问题的人。这是相同的代码片段:

public void runCommand() throws InterruptedException {
//Command to be run
String ssmCommand = "ls -l";
Map<String, List<String>> params = new HashMap<String, List<String>>(){{
put("commands", new ArrayList<String>(){{ add(ssmCommand); }});
}};
int timeoutInSecs = 5;
//You can add multiple command ids separated by commas
Target target = new Target().withKey("InstanceIds").withValues("instance-id");
//Create ssm client.
//The builder could be chosen as per your preferred way of authentication
//use withRegion for specifying your region
AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.standard().build();
//Build a send command request
SendCommandRequest commandRequest = new SendCommandRequest()
.withTargets(target)
.withDocumentName("AWS-RunShellScript")
.withParameters(params);
//The result has commandId which is used to track the execution further
SendCommandResult commandResult = ssm.sendCommand(commandRequest);
String commandId = commandResult.getCommand().getCommandId();
//Loop until the invocation ends
String status;
do {
ListCommandInvocationsRequest request = new ListCommandInvocationsRequest()
.withCommandId(commandId)
.withDetails(true);
//You get one invocation per ec2 instance that you added to target
//For just a single instance use get(0) else loop over the instanced
CommandInvocation invocation = ssm.listCommandInvocations(request).getCommandInvocations().get(0);
status = invocation.getStatus();
if(status.equals("Success")) {
//command output holds the output of running the command
//eg. list of directories in case of ls
String commandOutput = invocation.getCommandPlugins().get(0).getOutput();
//Process the output
}
//Wait for a few seconds before you check the invocation status again
try {
TimeUnit.SECONDS.sleep(timeoutInSecs);
} catch (InterruptedException e) {
//Handle not being able to sleep
}
} while(status.equals("Pending") || status.equals("InProgress"));
if(!status.equals("Success")) {
//Command ended up in a failure
}
}

关于amazon-web-services - AWS Java SDK - 在 EC2 实例上使用 SSM 运行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58627387/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com