

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 将 `ImportKeyPair` 与 CLI 配合使用
<a name="example_ec2_ImportKeyPair_section"></a>

以下代码示例演示如何使用 `ImportKeyPair`。

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

**AWS CLI**  
**导入公有密钥**  
首先，使用您选择的工具生成密钥对。例如，使用此 ssh-keygen 命令：  
命令:  

```
ssh-keygen -t rsa -C "my-key" -f ~/.ssh/my-key
```
输出：  

```
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/ec2-user/.ssh/my-key.
Your public key has been saved in /home/ec2-user/.ssh/my-key.pub.
...
```
此示例命令导入指定的公有密钥。  
命令:  

```
aws ec2 import-key-pair --key-name "my-key" --public-key-material fileb://~/.ssh/my-key.pub
```
输出：  

```
{
  "KeyName": "my-key",
  "KeyFingerprint": "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca"
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[ImportKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/import-key-pair.html)*中的。

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

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将公有密钥导入到 EC2。第一行将公有密钥文件 (\$1.pub) 的内容存储在变量 `$publickey` 中。接下来，该示例将公钥文件的 UTF8 格式转换为 Base64 编码的字符串，并将转换后的字符串存储在变量中。`$pkbase64`在最后一行中，将转换后的公有密钥导入到 EC2。cmdlet 将密钥指纹和名称作为结果返回。**  

```
$publickey=[Io.File]::ReadAllText("C:\Users\TestUser\.ssh\id_rsa.pub")
$pkbase64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($publickey))
Import-EC2KeyPair -KeyName Example-user-key -PublicKey $pkbase64
```
**输出**：  

```
KeyFingerprint                                  KeyName
--------------                                  -------
do:d0:15:8f:79:97:12:be:00:fd:df:31:z3:b1:42:z1 Example-user-key
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [ImportKeyPair](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将公有密钥导入到 EC2。第一行将公有密钥文件 (\$1.pub) 的内容存储在变量 `$publickey` 中。接下来，该示例将公钥文件的 UTF8 格式转换为 Base64 编码的字符串，并将转换后的字符串存储在变量中。`$pkbase64`在最后一行中，将转换后的公有密钥导入到 EC2。cmdlet 将密钥指纹和名称作为结果返回。**  

```
$publickey=[Io.File]::ReadAllText("C:\Users\TestUser\.ssh\id_rsa.pub")
$pkbase64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($publickey))
Import-EC2KeyPair -KeyName Example-user-key -PublicKey $pkbase64
```
**输出**：  

```
KeyFingerprint                                  KeyName
--------------                                  -------
do:d0:15:8f:79:97:12:be:00:fd:df:31:z3:b1:42:z1 Example-user-key
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ImportKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[使用 AWS SDK 创建 Amazon EC2 资源](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。