

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 搭配使用 `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 ]

**Tools for 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 參考 (V4)》**中的 [ImportKeyPair](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for 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 參考 (V5)》**中的 [ImportKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)。

------

如需 AWS SDK 開發人員指南和程式碼範例的完整清單，請參閱 [使用 SDK 建立 Amazon EC2 資源 AWS](sdk-general-information-section.md)。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。