将 SendCommand 与 Amazon SDK 或 CLI 配合使用 - Amazon Systems Manager
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

SendCommand 与 Amazon SDK 或 CLI 配合使用

以下代码示例演示如何使用 SendCommand

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

CLI
Amazon CLI

示例 1:在一个或多个远程实例上运行命令

以下 send-command 示例在目标实例上运行 echo 命令。

aws ssm send-command \ --document-name "AWS-RunShellScript" \ --parameters 'commands=["echo HelloWorld"]' \ --targets "Key=instanceids,Values=i-1234567890abcdef0" \ --comment "echo HelloWorld"

输出:

{ "Command": { "CommandId": "92853adf-ba41-4cd6-9a88-142d1EXAMPLE", "DocumentName": "AWS-RunShellScript", "DocumentVersion": "", "Comment": "echo HelloWorld", "ExpiresAfter": 1550181014.717, "Parameters": { "commands": [ "echo HelloWorld" ] }, "InstanceIds": [ "i-0f00f008a2dcbefe2" ], "Targets": [], "RequestedDateTime": 1550173814.717, "Status": "Pending", "StatusDetails": "Pending", "OutputS3BucketName": "", "OutputS3KeyPrefix": "", "MaxConcurrency": "50", "MaxErrors": "0", "TargetCount": 1, "CompletedCount": 0, "ErrorCount": 0, "DeliveryTimedOutCount": 0, "ServiceRole": "", "NotificationConfig": { "NotificationArn": "", "NotificationEvents": [], "NotificationType": "" }, "CloudWatchOutputConfig": { "CloudWatchLogGroupName": "", "CloudWatchOutputEnabled": false } } }

有关更多信息,请参阅《Amazon Systems Manager 用户指南》中的使用 Systems Manager Run Command 运行命令

示例 2:获取有关实例的 IP 信息

以下 send-command 示例检索关于实例的 IP 信息。

aws ssm send-command \ --instance-ids "i-1234567890abcdef0" \ --document-name "AWS-RunShellScript" \ --comment "IP config" \ --parameters "commands=ifconfig"

有关输出示例,请参阅示例 1。

有关更多信息,请参阅《Amazon Systems Manager 用户指南》中的使用 Systems Manager Run Command 运行命令

示例 3:在具有特定标签的实例上运行命令

以下 send-command 示例在标签键为“ENV”且值为“Dev”的实例上运行命令。

aws ssm send-command \ --targets "Key=tag:ENV,Values=Dev" \ --document-name "AWS-RunShellScript" \ --parameters "commands=ifconfig"

有关输出示例,请参阅示例 1。

有关更多信息,请参阅《Amazon Systems Manager 用户指南》中的使用 Systems Manager Run Command 运行命令

示例 4:运行发送 SNS 通知的命令

以下 send-command 示例运行一条命令,发送所有通知事件和 Command 通知类型的 SNS 通知。

aws ssm send-command \ --instance-ids "i-1234567890abcdef0" \ --document-name "AWS-RunShellScript" \ --comment "IP config" \ --parameters "commands=ifconfig" \ --service-role-arn "arn:aws:iam::123456789012:role/SNS_Role" \ --notification-config "NotificationArn=arn:aws:sns:us-east-1:123456789012:SNSTopicName,NotificationEvents=All,NotificationType=Command"

有关输出示例,请参阅示例 1。

有关更多信息,请参阅《Amazon Systems Manager 用户指南》中的使用 Systems Manager Run Command 运行命令

示例 5:运行输出到 S3 和 CloudWatch 的命令

以下 send-command 示例运行一条命令,将命令详细信息输出到 S3 存储桶和 CloudWatch Logs 日志组。

aws ssm send-command \ --instance-ids "i-1234567890abcdef0" \ --document-name "AWS-RunShellScript" \ --comment "IP config" \ --parameters "commands=ifconfig" \ --output-s3-bucket-name "s3-bucket-name" \ --output-s3-key-prefix "runcommand" \ --cloud-watch-output-config "CloudWatchOutputEnabled=true,CloudWatchLogGroupName=CWLGroupName"

有关输出示例,请参阅示例 1。

有关更多信息,请参阅《Amazon Systems Manager 用户指南》中的使用 Systems Manager Run Command 运行命令

示例 6:在具有不同标签的多个实例上运行命令

以下 send-command 示例对具有两个不同标签键和值的实例运行命令。

aws ssm send-command \ --document-name "AWS-RunPowerShellScript" \ --parameters commands=["echo helloWorld"] \ --targets Key=tag:Env,Values=Dev Key=tag:Role,Values=WebServers

有关输出示例,请参阅示例 1。

有关更多信息,请参阅《Amazon Systems Manager 用户指南》中的使用 Systems Manager Run Command 运行命令

示例 7:将具有相同标签键的多个实例设为目标

以下 send-command 示例在具有相同标签键但不同值的实例上运行命令。

aws ssm send-command \ --document-name "AWS-RunPowerShellScript" \ --parameters commands=["echo helloWorld"] \ --targets Key=tag:Env,Values=Dev,Test

有关输出示例,请参阅示例 1。

有关更多信息,请参阅《Amazon Systems Manager 用户指南》中的使用 Systems Manager Run Command 运行命令

示例 8:运行使用共享文档的命令

以下 send-command 示例在目标实例上运行共享文档。

aws ssm send-command \ --document-name "arn:aws:ssm:us-east-1:123456789012:document/ExampleDocument" \ --targets "Key=instanceids,Values=i-1234567890abcdef0"

有关输出示例,请参阅示例 1。

有关更多信息,请参阅《Amazon Systems Manager 用户指南》中的使用共享 SSM 文档

  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 SendCommand

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// Sends a SSM command to a managed node. public static String sendSSMCommand(SsmClient ssmClient, String documentName, String instanceId) throws InterruptedException { // Before we use Document to send a command - make sure it is active. boolean isDocumentActive = false; DescribeDocumentRequest request = DescribeDocumentRequest.builder() .name(documentName) .build(); while (!isDocumentActive) { DescribeDocumentResponse response = ssmClient.describeDocument(request); String documentStatus = response.document().statusAsString(); if (documentStatus.equals("Active")) { System.out.println("The Systems Manager document is active and ready to use."); isDocumentActive = true; } else { System.out.println("The Systems Manager document is not active. Status: " + documentStatus); try { // Add a delay to avoid making too many requests. Thread.sleep(5000); // Wait for 5 seconds before checking again } catch (InterruptedException e) { e.printStackTrace(); } } } // Create the SendCommandRequest. SendCommandRequest commandRequest = SendCommandRequest.builder() .documentName(documentName) .instanceIds(instanceId) .build(); // Send the command. SendCommandResponse commandResponse = ssmClient.sendCommand(commandRequest); String commandId = commandResponse.command().commandId(); System.out.println("The command Id is " + commandId); // Wait for the command execution to complete. GetCommandInvocationRequest invocationRequest = GetCommandInvocationRequest.builder() .commandId(commandId) .instanceId(instanceId) .build(); System.out.println("Wait 5 secs"); TimeUnit.SECONDS.sleep(5); // Retrieve the command execution details. GetCommandInvocationResponse commandInvocationResponse = ssmClient.getCommandInvocation(invocationRequest); // Check the status of the command execution. CommandInvocationStatus status = commandInvocationResponse.status(); if (status == CommandInvocationStatus.SUCCESS) { System.out.println("Command execution successful."); } else { System.out.println("Command execution failed. Status: " + status); } return commandId; }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API Reference》中的 SendCommand

PowerShell
适用于 PowerShell 的工具

示例 1:此示例在目标实例上运行 echo 命令。

Send-SSMCommand -DocumentName "AWS-RunPowerShellScript" -Parameter @{commands = "echo helloWorld"} -Target @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}

输出:

CommandId : d8d190fc-32c1-4d65-a0df-ff5ff3965524 Comment : CompletedCount : 0 DocumentName : AWS-RunPowerShellScript ErrorCount : 0 ExpiresAfter : 3/7/2017 10:48:37 PM InstanceIds : {} MaxConcurrency : 50 MaxErrors : 0 NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig OutputS3BucketName : OutputS3KeyPrefix : OutputS3Region : Parameters : {[commands, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]} RequestedDateTime : 3/7/2017 9:48:37 PM ServiceRole : Status : Pending StatusDetails : Pending TargetCount : 0 Targets : {instanceids}

示例 2:此示例展示如何运行接受嵌套参数的命令。

Send-SSMCommand -DocumentName "AWS-RunRemoteScript" -Parameter @{ sourceType="GitHub";sourceInfo='{"owner": "me","repository": "amazon-ssm","path": "Examples/Install-Win32OpenSSH"}'; "commandLine"=".\Install-Win32OpenSSH.ps1"} -InstanceId i-0cb2b964d3e14fd9f
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet Reference》中的 SendCommand

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

class DocumentWrapper: """Encapsulates AWS Systems Manager Document actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.name = None @classmethod def from_client(cls): ssm_client = boto3.client("ssm") return cls(ssm_client) def send_command(self, instance_ids): """ Sends a command to one or more instances. :param instance_ids: The IDs of the instances to send the command to. :return: The ID of the command. """ try: response = self.ssm_client.send_command( InstanceIds=instance_ids, DocumentName=self.name, TimeoutSeconds=3600 ) return response["Command"]["CommandId"] except ClientError as err: logger.error( "Couldn't send command to %s. Here's why: %s: %s", self.name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 SendCommand

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 Systems Manager 与 Amazon SDK 配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。