

• La AWS Systems Manager CloudWatch dashboard non sarà più disponibile dopo il 30 aprile 2026. I clienti possono continuare a utilizzare la CloudWatch console Amazon per visualizzare, creare e gestire le proprie CloudWatch dashboard Amazon, proprio come fanno oggi. Per ulteriori informazioni, consulta la [documentazione di Amazon CloudWatch Dashboard](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html). 

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Utilizzo `SendCommand` con un AWS SDK o una CLI
<a name="example_ssm_SendCommand_section"></a>

Gli esempi di codice seguenti mostrano come utilizzare `SendCommand`.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice: 
+  [Informazioni di base](example_ssm_Scenario_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**Esempio 1: eseguire un comando su una o più istanze remote**  
L’esempio seguente `send-command` esegue un comando `echo` su un’istanza di destinazione.  

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

```
{
    "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
        }
    }
}
```
Per ulteriori informazioni, consulta [Eseguire comandi utilizzando Systems Manager Run Command](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) nella *Guida per l’utente di AWS Systems Manager*.  
**Esempio 2: per ottenere informazioni IP su un'istanza**  
L’esempio seguente `send-command` recupera le informazioni sull’IP di un’istanza.  

```
aws ssm send-command \
    --instance-ids "i-1234567890abcdef0" \
    --document-name "AWS-RunShellScript" \
    --comment "IP config" \
    --parameters "commands=ifconfig"
```
Vedi l'esempio 1 per un output di esempio.  
Per ulteriori informazioni, consulta [Eseguire comandi utilizzando Systems Manager Run Command](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) nella *Guida per l'utente di AWS Systems Manager*.  
**Esempio 3: eseguire un comando su istanze con tag specifici**  
L’esempio seguente `send-command` esegue un comando sulle istanze che hanno la chiave di tag “ENV” e il valore “Dev”.  

```
aws ssm send-command \
    --targets "Key=tag:ENV,Values=Dev" \
    --document-name "AWS-RunShellScript" \
    --parameters "commands=ifconfig"
```
Vedi l'esempio 1 per un output di esempio.  
Per ulteriori informazioni, consulta [Eseguire comandi utilizzando Systems Manager Run Command](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) nella *Guida per l'utente di AWS Systems Manager*.  
**Esempio 4: come eseguire un comando che invia notifiche SNS**  
L’esempio seguente `send-command` esegue un comando che invia notifiche SNS per tutti gli eventi di notifica e il tipo di notifica `Command`.  

```
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"
```
Vedi l'esempio 1 per un output di esempio.  
Per ulteriori informazioni, consulta [Eseguire comandi utilizzando Systems Manager Run Command](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) nella *Guida per l'utente di AWS Systems Manager*.  
**Esempio 5: eseguire un comando che genera output su S3 e CloudWatch**  
L'`send-command`esempio seguente esegue un comando che invia i dettagli del comando a un bucket S3 e a un gruppo di log Logs. CloudWatch   

```
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"
```
Vedi l’esempio 1 per un output di esempio.  
Per ulteriori informazioni, consulta [Eseguire comandi utilizzando Systems Manager Run Command](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) nella *Guida per l'utente di AWS Systems Manager*.  
**Esempio 6: come eseguire comandi su più istanze con tag diversi**  
L’esempio seguente `send-command` esegue un comando su istanze con due chiavi e valori di tag diversi.  

```
aws ssm send-command \
    --document-name "AWS-RunPowerShellScript" \
    --parameters commands=["echo helloWorld"] \
    --targets Key=tag:Env,Values=Dev Key=tag:Role,Values=WebServers
```
Vedi l'esempio 1 per un output di esempio.  
Per ulteriori informazioni, consulta [Eseguire comandi utilizzando Systems Manager Run Command](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) nella *Guida per l'utente di AWS Systems Manager*.  
**Esempio 7: come indirizzare più istanze con la stessa chiave di tag**  
L’esempio seguente `send-command` esegue un comando su istanze che hanno la stessa chiave di tag ma con valori diversi.  

```
aws ssm send-command \
    --document-name "AWS-RunPowerShellScript" \
    --parameters commands=["echo helloWorld"] \
    --targets Key=tag:Env,Values=Dev,Test
```
Vedi l'esempio 1 per un output di esempio.  
Per ulteriori informazioni, consulta [Eseguire comandi utilizzando Systems Manager Run Command](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) nella *Guida per l'utente di AWS Systems Manager*.  
**Esempio 8: come eseguire un comando che utilizza un documento condiviso**  
L’esempio seguente `send-command` esegue un documento condiviso su un’istanza di destinazione.  

```
aws ssm send-command \
    --document-name "arn:aws:ssm:us-east-1:123456789012:document/ExampleDocument" \
    --targets "Key=instanceids,Values=i-1234567890abcdef0"
```
Vedi l'esempio 1 per un output di esempio.  
Per ulteriori informazioni, consulta [Utilizzo di documenti condivisi SSM](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-using-shared.html) nella *Guida per l’utente di AWS Systems Manager*.  
+  *Per i dettagli sull'API, consulta [SendCommand](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/send-command.html)Command Reference.AWS CLI * 

------
#### [ Java ]

**SDK per Java 2.x**  
 C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples). 

```
    /**
     * Sends a SSM command to a managed node asynchronously.
     *
     * @param documentName The name of the document to use.
     * @param instanceId The ID of the instance to send the command to.
     * @return The command ID.
     * <p>
     * This method initiates asynchronous requests to send a SSM command to a managed node.
     * It waits until the document is active, sends the command, and checks the command execution status.
     */
    public String sendSSMCommand(String documentName, String instanceId) throws InterruptedException, SsmException {
        // Before we use Document to send a command - make sure it is active.
        CompletableFuture<Void> documentActiveFuture = CompletableFuture.runAsync(() -> {
            boolean isDocumentActive = false;
            DescribeDocumentRequest request = DescribeDocumentRequest.builder()
                    .name(documentName)
                    .build();

            while (!isDocumentActive) {
                CompletableFuture<DescribeDocumentResponse> response = getAsyncClient().describeDocument(request);
                String documentStatus = response.join().document().statusAsString();
                if (documentStatus.equals("Active")) {
                    System.out.println("The SSM document is active and ready to use.");
                    isDocumentActive = true;
                } else {
                    System.out.println("The SSM document is not active. Status: " + documentStatus);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });

        documentActiveFuture.join();

        // Create the SendCommandRequest.
        SendCommandRequest commandRequest = SendCommandRequest.builder()
                .documentName(documentName)
                .instanceIds(instanceId)
                .build();

        // Send the command.
        CompletableFuture<SendCommandResponse> commandFuture = getAsyncClient().sendCommand(commandRequest);
        final String[] commandId = {null};

        commandFuture.whenComplete((commandResponse, ex) -> {
            if (commandResponse != null) {
                commandId[0] = commandResponse.command().commandId();
                System.out.println("Command ID: " + commandId[0]);

                // Wait for the command execution to complete.
                GetCommandInvocationRequest invocationRequest = GetCommandInvocationRequest.builder()
                        .commandId(commandId[0])
                        .instanceId(instanceId)
                        .build();

                try {
                    System.out.println("Wait 5 secs");
                    TimeUnit.SECONDS.sleep(5);

                    // Retrieve the command execution details.
                    CompletableFuture<GetCommandInvocationResponse> invocationFuture = getAsyncClient().getCommandInvocation(invocationRequest);
                    invocationFuture.whenComplete((commandInvocationResponse, invocationEx) -> {
                        if (commandInvocationResponse != null) {
                            // 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);
                            }
                        } else {
                            Throwable invocationCause = (invocationEx instanceof CompletionException) ? invocationEx.getCause() : invocationEx;
                            throw new CompletionException(invocationCause);
                        }
                    }).join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof SsmException) {
                    throw (SsmException) cause;
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();

        return commandId[0];
    }
```
+  Per i dettagli sull'API, [SendCommand](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/SendCommand)consulta *AWS SDK for Java 2.x API Reference*. 

------
#### [ JavaScript ]

**SDK per JavaScript (v3)**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples). 

```
import { SendCommandCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Send an SSM command to a managed node.
 * @param {{ documentName: string }}
 */
export const main = async ({ documentName }) => {
  const client = new SSMClient({});
  try {
    await client.send(
      new SendCommandCommand({
        DocumentName: documentName,
      }),
    );
    console.log("Command sent successfully.");
    return { Success: true };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ValidationError") {
      console.warn(`${caught.message}. Did you provide a valid document name?`);
    } else {
      throw caught;
    }
  }
};
```
+  Per i dettagli sull'API, [SendCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/SendCommandCommand)consulta *AWS SDK per JavaScript API Reference*. 

------
#### [ PowerShell ]

**Strumenti per PowerShell V4**  
**Esempio 1: questo esempio esegue un comando echo su un’istanza di destinazione.**  

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

```
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}
```
**Esempio 2: questo esempio mostra come eseguire un comando che accetta parametri annidati.**  

```
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
```
+  Per i dettagli sull'API, vedere [SendCommand](https://docs.aws.amazon.com/powershell/v4/reference)in *AWS Strumenti per PowerShell Cmdlet Reference (*V4). 

**Strumenti per V5 PowerShell **  
**Esempio 1: questo esempio esegue un comando echo su un’istanza di destinazione.**  

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

```
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}
```
**Esempio 2: questo esempio mostra come eseguire un comando che accetta parametri annidati.**  

```
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
```
+  Per i dettagli sull'API, vedere [SendCommand](https://docs.aws.amazon.com/powershell/v5/reference)in *AWS Strumenti per PowerShell Cmdlet Reference (*V5). 

------
#### [ Python ]

**SDK per Python (Boto3)**  
 C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples). 

```
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
```
+  Per i dettagli sull'API, consulta [SendCommand AWS](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/SendCommand)*SDK for Python (Boto3) API Reference*. 

------
#### [ SAP ABAP ]

**SDK per SAP ABAP**  
 C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples). 

```
    TRY.
        DATA(lo_result) = lo_ssm->sendcommand(
            it_instanceids = it_instance_ids
            iv_documentname = iv_document_name
            iv_timeoutseconds = 3600 ).
        DATA(lo_command) = lo_result->get_command( ).
        IF lo_command IS BOUND.
          rv_command_id = lo_command->get_commandid( ).
          MESSAGE 'Command sent successfully.' TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_ssminvaliddocument.
        MESSAGE 'Invalid document.' TYPE 'I'.
      CATCH /aws1/cx_ssminvalidinstanceid.
        MESSAGE 'Invalid instance ID.' TYPE 'I'.
    ENDTRY.
```
+  Per i dettagli sulle API, [SendCommand](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)consulta *AWS SDK for SAP ABAP* API reference. 

------

Per un elenco completo delle guide per sviluppatori AWS SDK e degli esempi di codice, consulta. [Utilizzo di questo servizio con un AWS SDK](sdk-general-information-section.md) Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell’SDK.