All Products
Search
Document Center

Elastic Compute Service:Connect to an instance with a temporary key pair by using Session Manager CLI

Last Updated:Jan 09, 2025

If you connect to a Linux Elastic Compute Service (ECS) instance by using the key pair-based authentication method from a third-party SSH tool, you can register a temporary public key that is valid for 60 seconds with the instance and use the corresponding private key to connect to the instance within the 60 seconds. Compared with permanent key pairs, temporary key pairs provide higher security in connections. This topic describes how to use Session Manager CLI (ali-instance-cli) to register a temporary public key with an ECS instance and connect to the instance with the corresponding private key instead of a password.

Temporary public keys

Temporary public keys allow you to securely connect to instances without the need to configure key pairs on the instances. Each time you want to connect to an instance over SSH, you can register a temporary public key that is valid for 60 seconds with the instance and then connect to the instance by using the corresponding private key instead of a password.

Note

Temporary public keys are stored in the Cloud Assistant server.

Preparations

Enable Session Manager

Before you can use ali-instance-cli, use your Alibaba Cloud account to enable Session Manager. You can enable Session Manager only in the ECS console. To enable Session Manager, perform the following steps:

  1. Log on to the ECS console.

  2. In the left-side navigation pane, choose Instances & Images > Instances.

  3. In the upper-left corner of the top navigation bar, select the resource group and region in which the instance that you want to connect to resides.

  4. On the Instance page, find the instance to which you want to connect and click Connect in the Actions column.

image

  1. Click Show Other Logon Methods.

  2. In the Session Manager section, turn on the switch to the right of Session Management Closed and follow the on-screen instructions to enable Session Manager.

image

image

Check whether the instance to which you want to connect is in the Running state

You can use Session Manager to connect to only instances in the Running state.

Use the ECS console

You can view the status of the instance on the Instance page in the ECS console.

For information about how to check the status of the instance, see View instance information.

image

image

Use Alibaba Cloud CLI

If you configured Alibaba Cloud CLI, run a command to call an API operation to query the status of the instance. For information about the parameters of the API operation, see DescribeInstanceStatus.

For example, to query the status of the instance whose ID is i-bp1****** and that resides in the China (Hangzhou) region, run the following command:
aliyun ecs DescribeInstanceStatus --region cn-hangzhou --RegionId 'cn-hangzhou' --InstanceId.1 'i-bp1******'

If the instance is in the Running state, the value of the Status parameter in the command output is Running.

{
  "TotalCount": 1,
  "RequestId": "A413****-****-****-****-****611B",
  "PageSize": 1,
  "PageNumber": 1,
  "InstanceStatuses": {
    "InstanceStatus": [
      {
        "Status": "Running",
        "InstanceId": "i-bp1******"
      }
    ]
  }
}

You can also run commands to call other operations to query the status of the instance, such as DescribeInstances. For more information, see DescribeInstances.

Call an API operation

Call the DescribeInstanceStatus or DescribeInstances operation to query the status of the instance. For more information, see DescribeInstanceStatus or DescribeInstances.

Check whether Cloud Assistant Agent is installed on the instance to which you want to connect

Session Manager depends on Cloud Assistant. You can use one of the following methods to check whether Cloud Assistant Agent is installed on the instance.

Cloud Assistant Agent is pre-installed on ECS instances that are created from Alibaba Cloud public images on or after December 1, 2017. For ECS instances created before December 1, 2017, you must manually install Cloud Assistant Agent. For more information, see Install Cloud Assistant Agent.

Use the ECS console

Session Manager is implemented based on Cloud Assistant. You need to install Cloud Assistant Agent on the instance. You can view the status of Cloud Assistant Agent on the ECS Cloud Assistant page in the ECS console.

Cloud Assistant Agent is pre-installed on ECS instances that are created from Alibaba Cloud public images on or after December 1, 2017. For ECS instances created before December 1, 2017, you must manually install Cloud Assistant Agent. For more information, see Install Cloud Assistant Agent.

image

image

For information about how to view the status of the Cloud Assistant Agent and handle anomalies, see View the status of Cloud Assistant and handle anomalies.

Use Alibaba Cloud CLI

If you configured Alibaba Cloud CLI, run a command to call the DescribeCloudAssistantStatus operation to check whether Cloud Assistant Agent is installed on the instance and supports Session Manager. For information about the parameters of the DescribeCloudAssistantStatus operation, see DescribeCloudAssistantStatus.

For example, if the instance is assigned an ID of i-bp1****** and resides in the China (Hangzhou) region, run the following command to check whether Cloud Assistant Agent is installed on the instance and supports Session Manager:
aliyun ecs DescribeCloudAssistantStatus --region cn-hangzhou --RegionId 'cn-hangzhou' --InstanceId.1 'i-bp1******'

If Cloud Assistant Agent is installed on the instance and supports Session Manager, the values of the CloudAssistantStatus and SupportSessionManager parameters in the command output are true.

{
  "TotalCount": 1,
  "PageSize": 1,
  "RequestId": "DB34****-****-****-****-****A749",
  "NextToken": "",
  "PageNumber": 1,
  "InstanceCloudAssistantStatusSet": {
    "InstanceCloudAssistantStatus": [
      {
        "CloudAssistantVersion": "2.2.3.857",
        "SupportSessionManager": true,
        "InstanceId": "i-bp1******",
        "InvocationCount": 4,
        "OSType": "Linux",
        "CloudAssistantStatus": "true",
        "LastHeartbeatTime": "2024-12-10T02:38:04Z",
        "LastInvokedTime": "2024-12-08T16:02:45Z",
        "ActiveTaskCount": 0
      }
    ]
  }
}

Call an API operation

Call the DescribeCloudAssistantStatus operation to check whether Cloud Assistant Agent is installed on the instance. For more information, see DescribeCloudAssistantStatus.

Prepare the credentials of the Resource Access Management (RAM) user as whom you want to use Session Manager

When you use ali-instance-cli, you must specify the AccessKey pair and Security Token Service (STS) token of the RAM user. When you connect to an instance by using Session Manager, the system verifies whether the RAM user who has the credentials also has the ecs:StartTerminalSession permission.

When you configure a custom policy, you can configure the Resource parameter to specify the ECS instances to which a RAM user can connect by using Session Manager. Sample policy:

{
  "Version": "1",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "ecs:StartTerminalSession",
      "Resource": "*"
    }
  ]
}

For information about the CredentialsURI and STS Token parameters, see Create an AccessKey pair and What is STS?

For information about how to grant permissions to a RAM user, see Grant permissions to a RAM user.

1. Install and configure ali-instance-cli

Note

If you already installed and configured ali-instance-cli, skip this step.

1.1 Install ali-instance-cli

Install ali-instance-cli on your computer. The installation operations vary based on the operating system.

Windows

Click here to download ali-instance-cli for Windows and save it to a folder on your computer.

In this example, ali-instance-cli is saved to the C:\Users\test folder on your computer.

macOS

Run the following command in the macOS terminal to download ali-instance-cli for macOS:

curl -O https://aliyun-client-assist.oss-accelerate.aliyuncs.com/session-manager/mac/ali-instance-cli

Run the following command to grant execute permissions on ali-instance-cli:

chmod a+x ali-instance-cli

Linux

Run the following command to install ali-instance-cli for Linux:

curl -O https://aliyun-client-assist.oss-accelerate.aliyuncs.com/session-manager/linux/ali-instance-cli

Run the following command to grant execute permissions on ali-instance-cli:

chmod a+x ali-instance-cli

1.2 Configure ali-instance-cli

When you use ali-instance-cli on your computer to connect to an instance, you must configure identity credentials, such as an AccessKey pair. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. For more information, see the Prepare the credentials of the Resource Access Management (RAM) user as whom you want to use Session Manager section of this topic.

Windows

  1. Right-click the Start icon and select Run. In the Run dialog box, enter cmd and press the Enter key to open a Command Prompt window.

  2. Run the following command to switch to the directory in which ali-instance-cli.exe resides. In this example, the C:\Users\test directory is used.

    cd C:\Users\test
  3. Configure credentials. The following types of credentials are supported:

    AccessKey pair

    Run the following command and configure the Access Key Id, Access Key Secret, and Region Id parameters as prompted:

    ali-instance-cli.exe configure --mode AK
    STS token

    Run the following command to configure credentials:

    ali-instance-cli.exe configure set --mode StsToken --region "<region>" --access-key-id "<ak>"  --access-key-secret "<sk>"   --sts-token "<sts_token>"

    Replace <region>, <ak>, <sk>, and <sts_token> with the actual region ID, AccessKey ID, AccessKey secret, and Security Token Service (STS) token.

    Credentials URI

    Run the following command and configure the Credentials URI and Region Id parameters as prompted:

    ali-instance-cli.exe configure --mode=CredentialsURI

    The following command output indicates that credentials are configured.

    image

macOS or Linux

  1. Go to the directory in which ali-instance-cli resides. In this example, the root directory (~) of the current user is used.

    cd ~
  2. Configure credentials.

    AccessKey pair

    Run the following command and configure the Access Key Id, Access Key Secret, and Region Id parameters as prompted:

    ./ali-instance-cli configure --mode AK
    STS token

    Run the following command to configure credentials:

    ./ali-instance-cli configure set --mode StsToken --region "<region>" --access-key-id "<ak>"  --access-key-secret "<sk>"   --sts-token "<sts_token>"

    Replace <region>, <ak>, <sk>, and <sts_token> with the actual region ID, AccessKey ID, AccessKey secret, and STS token.

    Credentials URI

    Run the following command and configure the Credentials URI and Region Id parameters as prompted:

    ./ali-instance-cli configure --mode=CredentialsURI

    The following command output indicates that credentials are configured.

    image

2. Register a temporary public key with the instance to which you want to connect

2.1 Obtain the ID of the instance

Obtain the ID of the instance with which you want to register a temporary public key.

Use the ECS console

  1. Log on to the ECS console.

  2. In the left-side navigation pane, choose Instances & Images > Instances.

  3. In the upper-left corner of the top navigation bar, select the resource group and region where the instance to which you want to connect resides.

  4. On the Instance page, find the instance to which you want to connect and click the instance ID.

image

Use Alibaba Cloud CLI

If you configured Alibaba Cloud CLI, run a command to call the DescribeInstances operation to query the ID of the instance to which you want to connect. For information about the parameters of the DescribeInstances operation, see DescribeInstances.

For example, run the following command to query the ID of an instance named SessionManager-example that resides in the China (Hangzhou) region:
aliyun ecs DescribeInstances --region cn-hangzhou --RegionId 'cn-hangzhou' --InstanceName 'SessionManager-example'

The value of the InstanceId parameter in the command output is the ID of the instance.

image

Call API operations

Call the DescribeInstances operation to query the ID of the instance to which you want to connect. For more information, see DescribeInstances.

2.2 Generate a key pair

Generate a pair of key files on your computer. The public key file is used for the temporary public key in Step 2.3.

Windows computer

Open Command Prompt and run the following command to generate a key pair as prompted.

In this example, the OpenSSH client is used to generate a key pair in the C:\Users\test directory.
ssh-keygen -t rsa -b 2048 -f id_rsa
  • -t rsa: specifies the Rivest-Shamir-Adleman (RSA) key type.

  • -b 2048: specifies a key length of 2,048 bits.

  • -f id_rsa: specifies that the key files named id_rsa are generated in the working directory.

Important

After you run the preceding command, you are prompted to enter a passphrase to protect the private key. After you configure a passphrase for the private key, anyone who wants to use the private key must first obtain the passphrase.

If you do not want to configure a passphrase for the private key, you can press the Enter key to skip the passphrase configuration step.

After you run the preceding command, the id_rsa.pub file, which is the public key file, and the id_rsa file, which is the private key file, are generated in the working directory of the command line. In this example, the working directory of the command line is C:\Users\test.

macOS or Linux computer

Open Terminal and run the following command to generate a key pair as prompted.

In this example, the OpenSSH client is used to generate a key pair.
ssh-keygen -t rsa -b 2048 -f id_rsa
  • -t rsa: specifies the RSA key type.

  • -b 2048: specifies a key length of 2,048 bits.

  • -f id_rsa: specifies that the key files named id_rsa are generated in the working directory.

Important

After you run the preceding command, you are prompted to enter a passphrase to protect the private key. After you configure a passphrase for the private key, anyone who wants to use the private key must first obtain the passphrase.

If you do not want to configure a passphrase for the private key, you can press the Enter key to skip the passphrase configuration step.

After you run the preceding command, the id_rsa.pub file, which is the public key file, and the id_rsa file, which is the private key file, are generated in the working directory of the command line.

2.3 Send the generated public key as a temporary public key to the instance

Windows computer

Open Command Prompt, switch to the directory where ali-instance-cli.exe resides, and then run the following command to send a temporary public key to register the key with an instance.

In the following command, replace <instance_id> with the ID of the instance with which you want to register a temporary public key, <public_key_path> with the path in which the public key file generated in Step 2.2 is stored, and <ecs_username> with the username to which you want to assign the temporary public key:
ali-instance-cli.exe send_public_key --instance <instance_id> --public-key <public_key_path> --user-name <ecs_username>

For example, to register the temporary public key stored in the C:\Users\test\id_rsa.pub path on your computer with the instance whose ID is i-bp1****** and assign the key to the ecs-user user on the instance, run the following command:

ali-instance-cli.exe send_public_key --instance i-bp1****** --public-key C:\Users\test\id_rsa.pub --user-name ecs-user
Important

After the command is successfully run, log on to the instance by using the corresponding private key within 60 seconds.

macOS or Linux computer

Open Terminal, switch to the directory where ali-instance-cli resides, and then run the following command to send a temporary public key to register the key with an instance.

In the following command, replace <instance_id> with the ID of the instance with which you want to register a temporary public key, <public_key_path> with the path in which the public key file generated in Step 2.2 is stored, and <ecs_username> with the username to which you want to assign the temporary public key:
./ali-instance-cli send_public_key --instance <instance_id> --public-key <public_key_path> --user-name <ecs_username>

For example, to register a temporary public key stored in the ~/id_rsa.pub path on your computer with the instance whose ID is i-bp1****** and assign the key to the ecs-user user on the instance, run the following command:

./ali-instance-cli send_public_key --instance i-bp1****** --public-key ~/id_rsa.pub --user-name ecs-user
Important
  • After the command is successfully run, log on to the instance by using the corresponding private key within 60 seconds.

After you run the command, the ERROR: 'install config_ecs_instance_connect' command failed error message appears

If the ERROR: 'install config_ecs_instance_connect' command failed error message appears after you run the command, the config_ecs_instance_connect Cloud Assistant plug-in fails to be installed on the instance as expected. Rerun the command. If the error message reappears, use one of the following methods to install the Cloud Assistant plug-in on the instance:

Use the ECS console

To install and start the config_ecs_instance_connect Cloud Assistant plug-in on an instance, use Cloud Assistant to send the following command to the instance.

For more information, see Create and run a command.

acs-plugin-manager -e -P config_ecs_instance_connect --params --install

Use the CLI

Note

In this example, i-bp15vhvt43ciprqkxxxx is used as the instance ID. Replace it with an actual value.

aliyun ecs RunCommand --RegionId 'cn-hangzhou' \
 --Type 'RunShellScript' \
 --CommandContent 'acs-plugin-manager -e -P config_ecs_instance_connect --params --install' \
 --InstanceId.1 'i-bp15vhvt43ciprqkxxxx'    

3. Connect to the instance over SSH

Important

If you are prompted that the specified password or public key is incorrect, check whether the public key has expired. A temporary public key is valid for 60 seconds.

Use an appropriate SSH tool to connect to the instance. Open Command Prompt or Terminal on your computer and run the following command to connect to the instance.

In the following command, replace <private_key_path> with the path in which the private key file generated in Step 2.2 is stored, <ecs-username> with the username that you specified for the public key in Step 2.3, and <ecs_ip> with the public IP address of the instance to which you want to connect.
ssh -i <private_key_path> <ecs-username>@<ecs_ip>

For example, to use the private key file that is stored in the ~/id_rsa path to connect to the instance whose public IP address is 223.***.***.187 as the ecs-user user, run the following command:

ssh -i ~/id_rsa ecs-user@223.***.***.187

You can also use the port forwarding feature of ali-instance-cli to connect to an instance that does not have a public IP address. For more information, see Use the port forwarding feature of Session Manager CLI to connect to an instance without a public IP address.

FAQ

What do I do if the command line does not respond after I run an ali-instance-cli command? (The instance may not be in the Running state)

If the command line does not respond after you run an ali-instance-cli command, the corresponding instance may not be in the Running state. Check the status of the instance. For more information, see the Check whether the instance to which you want to connect is in the Running state section of this topic.

What do I do if the command line does not respond after I run an ali-instance-cli command? (The required ports may not be open in security groups)

If the command line does not respond after you run an ali-instance-cli command, the required ports may not be open for outbound traffic in the security groups of the corresponding instance. By default, basic security groups open all ports for outbound traffic. The preceding issue may occur if you modify the outbound rules of basic security groups or use advanced security groups for the instance.

When you use Session Manager to connect to an ECS instance, make sure that Cloud Assistant Agent running on the ECS instance is connected to the Cloud Assistant server by adding the following rules to an outbound security group:

Compared with connection methods, such as SSH and Remote Desktop Protocol (RDP), Cloud Assistant Agent actively establishes a WebSocket connection to the Session Manager server. You need to only open the outbound WebSocket port of the Cloud Assistant server in a security rule. For information about how Session Manager works, see the How Session Manager works section of this topic.
Important
  • If you use basic security groups including the default security group, all outbound traffic is allowed. No additional configuration is required.

  • If you use an advanced security group, all outbound traffic is denied. You must configure the relevant rules. The following table describes the rules. For information about security groups, see Basic security groups and advanced security groups.

For information about how to add rules to a security group, see Add a security group rule.

Action

Priority

Protocol type

Port range

Authorization object

Description

Allow

1

Custom TCP

443

100.100.0.0/16

This port is used to access the Cloud Assistant server.

Allow

1

Custom TCP

443

100.0.0.0/8

This port is used to access the server on which the Cloud Assistant Agent installation package is stored when you want to install or update Cloud Assistant Agent.

Allow

1

Custom UDP

53

0.0.0.0/0

This port is used to resolve domain names.

If you want to connect to an instance by using only Session Manager, delete the inbound rules that allow the SSH port (default 22) and RDP port (default 3389) from a security group to improve the security of the ECS instance.

What do I do if the DeliveryTimeout error is reported after I run an ali-instance-cli command?

If the DeliveryTimeout error is reported as shown in the following figure after you run an ali-instance-cli command, Cloud Assistant Agent may be unavailable on the corresponding instance. Check the status of Cloud Assistant Agent. For more information, see the Check whether Cloud Assistant Agent is installed on the instance to which you want to connect section of this topic.

image

image

What do I do if the session manager is disabled, please enable first error message appears after I run an ali-instance-cli command?

If the session manager is disabled, please enable first error message appears after you run an ali-instance-cli command, Session Manager is disabled. Enable Session Manager in the ECS console. For more information, see the Enable Session Manager section of this topic.

What do I do if a connection established to an instance by using Session Manager is automatically closed due to inactivity for an extended period of time?

After you connect to an instance by using Session Manager, the connection is automatically closed if you do not perform operations for an extended period of time. By default, the idle timeout period for a connection is 3 minutes. You can use the --idle-timeout parameter to specify a custom idle timeout period.

For example, run the following command to connect to an instance and configure the connection to be automatically closed after 10 minutes of inactivity.

./ali-instance-cli session --instance instance-id --idle-timeout 600
Note

Make sure that the version of ali-instance-cli is not earlier than the following versions:

  • Linux: 1.2.0.48

  • Windows: 1.1.0.48

  • macOS: 1.3.0.48

How do I view logs about ali-instance-cli?

If an error occurs when you use ali-instance-cli, you can view logs to identify and troubleshoot the issue.

  • View the logs of ali-instance-cli. When you use ali-instance-cli, a log directory is generated in the directory in which ali-instance-cli resides. Example: ~/log/aliyun_ecs_session_log.2022XXXX. You can view the logs of ali-instance-cli in the log directory.

  • View the logs of Cloud Assistant Agent in one of the following directories based on the operating system:

    • Linux

      /usr/local/share/aliyun-assist/<Version number of Cloud Assistant Agent>/log/
    • Windows

      C:\ProgramData\aliyun\assist\<Version number of Cloud Assistant Agent>\log