本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用 &EC2; 密钥对
先决条件
在开始之前,建议您先阅读开始使用适用于 C++ 的 AWS SDK。
下载示例代码并按代码示例入门中所述构建解决方案。
要运行这些示例,您的代码用于发出请求的用户配置文件必须在 AWS 中具有适当的权限(用于服务和操作)。有关更多信息,请参阅提供 AWS 凭证。
创建密钥对
要创建密钥对,请使用包含密钥名称的 CreateKeyPairRequest 调用 EC2Client 的 CreateKeyPair 函数。
包含
#include <aws/ec2/EC2Client.h> #include <aws/ec2/model/CreateKeyPairRequest.h> #include <iostream> #include <fstream>
代码
Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::CreateKeyPairRequest request; request.SetKeyName(keyPairName); Aws::EC2::Model::CreateKeyPairOutcome outcome = ec2Client.CreateKeyPair(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to create key pair - " << keyPairName << ". " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully created key pair named " << keyPairName << std::endl; if (!keyFilePath.empty()) { std::ofstream keyFile(keyFilePath.c_str()); keyFile << outcome.GetResult().GetKeyMaterial(); keyFile.close(); std::cout << "Keys written to the file " << keyFilePath << std::endl; } }
请参阅完整示例
描述密钥对
要列出密钥对或获取相关信息,请使用 DescribeKeyPairsRequest 调用 EC2Client 的 DescribeKeyPairs 函数。
您将收到一个 DescribeKeyPairsResponse,通过调用其 GetKeyPairs 函数,您可以访问密钥对列表,该函数会返回一个 KeyPairInfo 对象列表。
包含
#include <aws/ec2/EC2Client.h> #include <aws/ec2/model/DescribeKeyPairsRequest.h> #include <aws/ec2/model/DescribeKeyPairsResponse.h> #include <iomanip> #include <iostream>
代码
Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::DescribeKeyPairsRequest request; Aws::EC2::Model::DescribeKeyPairsOutcome outcome = ec2Client.DescribeKeyPairs(request); if (outcome.IsSuccess()) { std::cout << std::left << std::setw(32) << "Name" << std::setw(64) << "Fingerprint" << std::endl; const std::vector<Aws::EC2::Model::KeyPairInfo> &key_pairs = outcome.GetResult().GetKeyPairs(); for (const auto &key_pair: key_pairs) { std::cout << std::left << std::setw(32) << key_pair.GetKeyName() << std::setw(64) << key_pair.GetKeyFingerprint() << std::endl; } } else { std::cerr << "Failed to describe key pairs:" << outcome.GetError().GetMessage() << std::endl; }
请参阅完整示例
删除密钥对
要删除密钥对,请调用 EC2Client 的 DeleteKeyPair 函数,并向其传递一个包含要删除密钥对名称的 DeleteKeyPairRequest。
包含
#include <aws/ec2/EC2Client.h> #include <aws/ec2/model/DeleteKeyPairRequest.h> #include <iostream>
代码
Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::DeleteKeyPairRequest request; request.SetKeyName(keyPairName); const Aws::EC2::Model::DeleteKeyPairOutcome outcome = ec2Client.DeleteKeyPair( request); if (!outcome.IsSuccess()) { std::cerr << "Failed to delete key pair " << keyPairName << ":" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully deleted key pair named " << keyPairName << std::endl; }
请参阅完整示例
更多信息
-
《Amazon EC2 用户指南》中的 Amazon EC2 密钥对
-
《Amazon EC2 API 参考》中的 CreateKeyPair
-
《Amazon EC2 API 参考》中的 DescribeKeyPairs
-
《Amazon EC2 API 参考》中的 DeleteKeyPair