Amazon EC2 uses public–key cryptography to encrypt and decrypt login information. Public–key cryptography uses a public key to encrypt a piece of data, such as a password, then the recipient uses the private key to decrypt the data. The public and private keys are known as a key pair.
To log in to your instance, you must create a key pair, specify the name of the key pair when you launch the instance, and provide the private key when you connect to the instance. Linux instances have no password, and you use a key pair to log in using SSH.
Creating a Key Pair
You can use Amazon EC2 to create your key pair. For more information, see Creating Your Key Pair Using Amazon EC2.
Alternatively, you could use a third-party tool and then import the public key to Amazon EC2. For more information, see Importing Your Own Key Pair to Amazon EC2.
Each key pair requires a name. Be sure to choose a name that is easy to remember. Amazon EC2 associates the public key with the name that you specify as the key name.
Amazon EC2 stores the public key only, and you store the private key. Anyone who possesses your private key can decrypt your login information, so it's important that you store your private keys in a secure place.
The keys that Amazon EC2 uses are 1024-bit SSH-2 RSA keys. You can have up to five thousand key pairs per region.
Launching and Connecting to Your Instance
When you launch an instance, you should specify the name of the key pair you plan to use to connect to the instance. If you don't specify the name of an existing key pair when you launch an instance, you won't be able to connect to the instance. When you connect to the instance, you must specify the private key that corresponds to the key pair you specified when you launched the instance. Amazon EC2 doesn't keep a copy of your private key; therefore, if you lose your private key, there is no way to recover it. If you lose the private key for an instance store-backed instance, you can't access the instance; you should terminate the instance and launch another instance using a new key pair. If you lose the private key for an EBS-backed instance, you can regain access to your instance. For more information, see Connecting to Your Linux Instance if You Lose Your Private Key.
Topics
Creating Your Key Pair Using Amazon EC2
You can create a key pair using the Amazon EC2 console or the command line.
To create your key pair using the console
-
Open the Amazon EC2 console.
-
From the navigation bar, select a region for the key pair. You can select any region that's available to you, regardless of your location. This choice is important because some Amazon EC2 resources can be shared between regions, but key pairs can't. For example, if you create a key pair in the US West (Oregon) region, you can't see or use the key pair in another region.
-
Click Key Pairs in the navigation pane.
-
Click Create Key Pair.
-
Enter a name for the new key pair in the Key pair name field of the Create Key Pair dialog box, and then click Create.
-
The private key file is automatically downloaded by your browser. The base file name is the name you specified as the name of your key pair, and the file name extension is
.pem
. Save the private key file in a safe place.Important
This is the only chance for you to save the private key file. You'll need to provide the name of your key pair when you launch an instance and the corresponding private key each time you connect to the instance.
-
If you will use an SSH client on a Mac or Linux computer to connect to your Linux instance, use the following command to set the permissions of your private key file so that only you can read it.
$
chmod 400
my-key-pair
.pem
To create your key pair using the command line
You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2.
-
create-key-pair (AWS CLI)
-
ec2-create-keypair (Amazon EC2 CLI)
-
New-EC2KeyPair (AWS Tools for Windows PowerShell)
Importing Your Own Key Pair to Amazon EC2
If you used Amazon EC2 to create your key pair, as described in the previous section, you are ready to launch an instance. Otherwise, instead of using Amazon EC2 to create your key pair, you can create an RSA key pair using a third-party tool and then import the public key to Amazon EC2. For example, you can use ssh-keygen (a tool provided with the standard OpenSSH installation) to create a key pair. Alternatively, Java, Ruby, Python, and many other programming languages provide standard libraries that you can use to create an RSA key pair.
Amazon EC2 accepts the following formats:
-
OpenSSH public key format (the format in
~/.ssh/authorized_keys
) -
Base64 encoded DER format
-
SSH public key file format as specified in RFC4716
Amazon EC2 does not accept DSA keys. Make sure your key generator is set up to create RSA keys.
Supported lengths: 1024, 2048, and 4096.
To create a key pair using a third-party tool
-
Generate a key pair with a third-party tool of your choice.
-
Save the public key to a local file. For example,
~/.ssh/my-key-pair.pub
. The file name extension for this file is not important. -
Save the private key to a different local file that has the
.pem
extension. For example,~/.ssh/my-key-pair.pem
. Save the private key file in a safe place. You'll need to provide the name of your key pair when you launch an instance and the corresponding private key each time you connect to the instance.
Use the following steps to import your key pair using the Amazon EC2 console. (If you prefer, you can use the ec2-import-keypair command or the ImportKeyPair action to import the public key.)
To import the public key
-
Open the Amazon EC2 console.
-
From the navigation bar, select the region for the key pair. This choice is important because key pair resources cannot be shared between regions. For example, if you import a key pair into the US West (Oregon) region, you won't be able to see or use the key pair in another region.
-
Click Key Pairs in the navigation pane.
-
Click Import Key Pair.
-
In the Import Key Pair dialog box, click Browse, and select the public key file that you saved previously. Enter a name for the key pair in the Key pair name field, and click Import.
After the public key file is imported, you can verify that the key pair was imported successfully using the Amazon EC2 console as follows. (If you prefer, you can use the ec2-describe-keypairs command or the DescribeKeyPairs action to list your key pairs.)
Retrieving the Public Key for Your Key Pair
On a Linux instance, the public key content is placed in an entry within ~/.ssh/authorized_keys
. This is done at boot time and enables you to securely access your instance without passwords. You can open this file in an editor to view the public key for your key pair. The following is an example entry for the key pair named my-key-pair. It consists of the public key followed by the name of the key pair. For example:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQClKsfkNkuSevGj3eYhCe53pcjqP3maAhDFcvBS7O6V hz2ItxCih+PnDSUaw+WNQn/mZphTk/a/gU8jEzoOWbkM4yxyb/wB96xbiFveSFJuOp/d6RJhJOI0iBXr lsLnBItntckiJ7FbtxJMXLvvwJryDUilBMTjYtwB+QhYXUMOzce5Pjz5/i8SeJtjnV3iAoG/cQk+0FzZ qaeJAAHco+CY/5WrUBkrHmFJr6HcXkvJdWPkYQS3xqC0+FmUZofz221CBt5IMucxXPkX4rWi+z7wB3Rb BQoQzd8v7yeb7OzlPnWOyN0qFU0XA246RA8QFYiCNYwI3f05p6KLxEXAMPLE my-key-pair
You can use ssh-keygen to get the public key for your key pair. Run the following command on a computer to which you've downloaded your private key:
$
ssh-keygen -y
When prompted to enter the file in which the key is, specify the path to your .pem
file; for example:
/path_to_key_pair
/my-key-pair.pem
The command returns the public key:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQClKsfkNkuSevGj3eYhCe53pcjqP3maAhDFcvBS7O6V hz2ItxCih+PnDSUaw+WNQn/mZphTk/a/gU8jEzoOWbkM4yxyb/wB96xbiFveSFJuOp/d6RJhJOI0iBXr lsLnBItntckiJ7FbtxJMXLvvwJryDUilBMTjYtwB+QhYXUMOzce5Pjz5/i8SeJtjnV3iAoG/cQk+0FzZ qaeJAAHco+CY/5WrUBkrHmFJr6HcXkvJdWPkYQS3xqC0+FmUZofz221CBt5IMucxXPkX4rWi+z7wB3Rb BQoQzd8v7yeb7OzlPnWOyN0qFU0XA246RA8QFYiCNYwI3f05p6KLxEXAMPLE
If this command fails, ensure that you've changed the permissions on your key pair file so that only you can view it by running the following command:
$
chmod 400
my-key-pair
.pem
The public key that you specified when you launched an instance is also available to you through its instance metadata. To view the public key that you specified when launching the instance, use the following command from your instance:
$
GET http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQClKsfkNkuSevGj3eYhCe53pcjqP3maAhDFcvBS7O6V hz2ItxCih+PnDSUaw+WNQn/mZphTk/a/gU8jEzoOWbkM4yxyb/wB96xbiFveSFJuOp/d6RJhJOI0iBXr lsLnBItntckiJ7FbtxJMXLvvwJryDUilBMTjYtwB+QhYXUMOzce5Pjz5/i8SeJtjnV3iAoG/cQk+0FzZ qaeJAAHco+CY/5WrUBkrHmFJr6HcXkvJdWPkYQS3xqC0+FmUZofz221CBt5IMucxXPkX4rWi+z7wB3Rb BQoQzd8v7yeb7OzlPnWOyN0qFU0XA246RA8QFYiCNYwI3f05p6KLxEXAMPLE my-key-pair
For more information, see Retrieving Instance Metadata.
Note that if you change the key pair that you use to connect to the instance, as shown in the last section on this page, we don't update the instance metadata to show the new public key; you'll continue to see the public key for the key pair you specified when you launched the instance in the instance metadata.
Verifying Your Key Pair's Fingerprint
On the Key Pairs page in the Amazon EC2 console, the Fingerprint column displays the fingerprints generated from your key pairs. AWS calculates the fingerprint differently depending on whether the key pair was generated by AWS or a third-party tool. If you created the key pair using AWS, the fingerprint is calculated using an SHA-1 hash function. If you created the key pair with a third-party tool and uploaded the public key to AWS, or if you generated a new public key from an existing AWS-created private key and uploaded it to AWS, the fingerprint is calculated using an MD5 hash function.
You can use the fingerprint that's displayed on the Key Pairs page to verify that the private key you have on your local machine matches the public key that's stored in AWS.
If you created your key pair using AWS, you can use the ec2-fingerprint-key command in the Amazon EC2 CLI to generate a fingerprint from the private key file on your local machine. The output should match the fingerprint that's displayed in the console. Alternatively, you can use the OpenSSL tools to generate a fingerprint from the private key file:
$
openssl pkcs8 -in
path_to_private_key
-inform PEM -outform DER -topk8 -nocrypt | openssl sha1 -c
If you created your key pair using a third-party tool and uploaded the public key to AWS, you can use the OpenSSL tools to generate a fingerprint from the private key file on your local machine:
$
openssl rsa -in
path_to_private_key
-pubout -outform DER | openssl md5 -c
The output should match the fingerprint that's displayed in the console.
Deleting Your Key Pair
When you delete a key pair, you are only deleting Amazon EC2's copy of the public key. Deleting a key pair doesn't affect the private key on your computer or the public key on any instances already launched using that key pair. You can't launch a new instance using a deleted key pair, but you can continue to connect to any instances that you launched using a deleted key pair, as long as you still have the private key (.pem
) file.
You can delete a key pair using the Amazon EC2 console or the command line.
To delete your key pair using the console
-
Open the Amazon EC2 console.
-
Click Key Pairs in the navigation pane.
-
Select the key pair and click Delete.
-
When prompted, click Yes.
To delete your key pair using the command line
You can use one of the following commands. For more information about these command line interfaces, see Accessing Amazon EC2.
-
delete-key-pair (AWS CLI)
-
ec2-delete-keypair (Amazon EC2 CLI)
-
Remove-EC2KeyPair (AWS Tools for Windows PowerShell)
Connecting to Your Linux Instance if You Lose Your Private Key
If you lose the private key for an EBS-backed instance, you can regain access to your instance. You must stop the instance, detach its root volume and attach it to another instance as a data volume, modify the authorized_keys
file, move the volume back to the original instance, and restart the instance. For more information about launching, connecting to, and stopping instances, see Instance Lifecycle.
This procedure isn't supported for instance store-backed instances. To determine the root device type of your instance, open the Amazon EC2 console, click Instances, select the instance, and check the value of Root device type in the details pane. The value is either ebs
or instance store
. If the root device is an instance store volume, you must have the private key in order to connect to the instance.
Tip
If the root volume of the instance has an AWS Marketplace product code, you can only attach it to an instance as the root device, not a secondary device. To determine whether a volume has an AWS Marketplace product code, select the instance, and check the value of Product codes in the details pane. If your volume has an AWS Marketplace product code and you need to complete this procedure, create a snapshot of the EBS volume, and then post a request to the Amazon EC2 forum to recover a instance with an AWS Marketplace product code. Include the Availability Zone, instance ID, AMI ID, and snapshot ID in the request. Someone from support will respond with further directions.
Prerequisites
Create a new key pair using either the Amazon EC2 console or a third-party tool.
To connect to an EBS-backed instance with a different key pair
-
From the Amazon EC2 console, click Instances in the navigation pane, and select the instance that you'd like to connect to. (We'll refer to this as the original instance.)
-
Save the following information that you'll see to complete this procedure.
-
Write down the instance ID (i-xxxxxxxx), AMI ID (ami-xxxxxxxx), and Availability Zone of the original instance.
-
Click the entry for
sda1
(the root volume) under Block devices in the details pane and write down the volume ID (vol-xxxxxxxx). -
[EC2-Classic] If the original instance has an associated Elastic IP address, write down the Elastic IP address shown under Elastic IP in the details pane.
-
-
Click Actions, and then click Stop. If Stop is disabled, either the instance is already stopped or its root device is an instance store volume.
-
Launch a temporary instance using the console with the following options:
-
On the Choose an AMI page, select the same AMI that you used to launch the original instance. If this AMI is unavailable, you can create an AMI that you can use from the stopped instance. For more information, see Creating an Amazon EBS-Backed Linux AMI .
-
On the Choose an Instance Type page, leave the default instance type that the wizard selects for you.
-
On the Configure Instance Details page, specify the same Availability Zone as the instance you'd like to connect to. If you're launching an instance in a VPC, select a subnet in this Availability Zone.
-
On the Tag Instance page, add the tag
Name=Temporary
to the instance to indicate that this is a temporary instance. -
On the Review page, click Launch. Specify the new key pair that you created, and then click Launch Instances.
-
-
In the navigation pane, click Volumes and select the root device volume for the original instance (you wrote down its volume ID in a previous step). Click Actions, and then click Detach Volume. Wait for the state of the volume to become
available
. (You might need to click the Refresh icon.) -
With the volume still selected, click Actions, and then click Attach Volume. Select the instance ID of the temporary instance, write down the device name specified under Device (for example,
/dev/sdf
), and then click Yes, Attach.Note
If the volume has an AWS Marketplace product code, you'll get an error indicating that you can't attach the volume as a secondary device. For more information, see the tip at the start of this section.
-
Connect to the temporary instance.
-
From the temporary instance, mount the volume that you attached to the instance so that you can access its file system. For example, if the device name is
/dev/sdf
, use the following commands to mount the volume as/mnt/tempvol
.Note
The device name may appear differently on your instance. For example, devices mounted as
/dev/sdf
may show up as/dev/xvdf
on the instance. Some versions of Red Hat (or its variants, such as CentOS) may even increment the trailing letter by 4 characters, where/dev/sd
becomesf
/dev/xvd
.k
-
Use the lsblk command to determine if the volume is partitioned.
[ec2-user ~]$
lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT xvda 202:0 0 8G 0 disk └─xvda1 202:1 0 8G 0 part / xvdf 202:80 0 101G 0 disk └─xvdf1 202:81 0 101G 0 part xvdg 202:96 0 30G 0 diskIn the above example,
/dev/xvda
and/dev/xvdf
are partitioned volumes, and/dev/xvdg
is not. If your volume is partitioned, you mount the partition (/dev/xvdf1)
instead of the raw device (/dev/xvdf
) in the next steps. -
Create a temporary directory to mount the volume.
[ec2-user ~]$
sudo mkdir /mnt/tempvol
-
Mount the volume (or partition) at the temporary mount point, using the volume name or device name you identified earlier.
[ec2-user ~]$
sudo mount /dev/
xvdf1
/mnt/tempvol
-
-
From the temporary instance, use the following command to update
authorized_keys
on the mounted volume with the new public key from theauthorized_keys
for the temporary instance (you may need to substitute a different user name in the following command, such asubuntu
for Ubuntu instances):[ec2-user ~]$
cp .ssh/authorized_keys /mnt/tempvol/home/
ec2-user
/.ssh/authorized_keysIf this copy succeeded, you can go to the next step.
(Optional) Otherwise, if you don't have permission to edit files in
/mnt/tempvol
, you'll need to update the file using sudo and then check the permissions on the file to verify that you'll be able to log into the original instance. Use the following command to check the permissions on the file:[ec2-user ~]$
sudo ls -l /mnt/home/ec2-user/.ssh
total 4 -rw------- 1222 500
398 Sep 13 22:54 authorized_keysIn this example output,
222
is the user ID and500
is the group ID. Next, use sudo to re-run the copy command that failed:[ec2-user ~]$
sudo cp .ssh/authorized_keys /mnt/tempvol/home/
ec2-user
/.ssh/authorized_keysRun the following command again to determine whether the permissions changed:
[ec2-user ~]$
sudo ls -l /mnt/home/
ec2-user
/.sshIf the user ID and group ID have changed, use the following command to restore them:
[ec2-user ~]$
sudo chown
222:500
/mnt/home/ec2-user
/.ssh/authorized_keys -
From the temporary instance, unmount the volume that you attached so that you can reattach it to the original instance. For example, use the following command to unmount the volume at
/mnt/tempvol
:[ec2-user ~]$
sudo umount /mnt/tempvol
-
From the Amazon EC2 console, select the volume with the volume ID that you wrote down, click Actions, and then click Detach Volume. Wait for the state of the volume to become
available
. (You might need to click the Refresh icon.) -
With the volume still selected, click Actions, and then click Attach Volume. Select the instance ID of the original instance, specify the device name
/dev/sda1
, and then click Yes, Attach.Warning
If you don't specify
sda1
as the device name, you'll be unable to start the original instance. This is because Amazon EC2 expects the root device volume atsda1
. -
Select the original instance, click Actions, and then click Start. After the instance enters the
running
state, you can connect to it using the private key file for your new key pair. -
[EC2-Classic] If the original instance had an associated Elastic IP address before you stopped it, you must re-associate it with the instance as follows:
-
In the navigation pane, click Elastic IPs.
-
Select the Elastic IP address that you wrote down at the beginning of this procedure.
-
Click Associate Address.
-
Select the ID of the original instance, and then click Associate.
-
-
(Optional) You can terminate the temporary instance if you have no further use for it. Select the temporary instance, click Actions, and then click Terminate.
转自:http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html