Utilizzare DescribeKeyPairs con un o AWS SDK CLI - Esempi di codice dell'AWS SDK

Ci sono altri AWS SDK esempi disponibili nel repository AWS Doc SDK Examples GitHub .

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Utilizzare DescribeKeyPairs con un o AWS SDK CLI

I seguenti esempi di codice mostrano come utilizzareDescribeKeyPairs.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice:

.NET
AWS SDK for .NET
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <summary> /// Get information about an Amazon EC2 key pair. /// </summary> /// <param name="keyPairName">The name of the key pair.</param> /// <returns>A list of key pair information.</returns> public async Task<List<KeyPairInfo>> DescribeKeyPairs(string keyPairName) { var request = new DescribeKeyPairsRequest(); if (!string.IsNullOrEmpty(keyPairName)) { request = new DescribeKeyPairsRequest { KeyNames = new List<string> { keyPairName } }; } var response = await _amazonEC2.DescribeKeyPairsAsync(request); return response.KeyPairs.ToList(); }
Bash
AWS CLI con lo script Bash
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

############################################################################### # function ec2_describe_key_pairs # # This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) key pairs. # # Parameters: # -h - Display help. # # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_describe_key_pairs() { local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_describe_key_pairs" echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) key pairs." echo " -h - Display help." echo "" } # Retrieve the calling parameters. while getopts "h" option; do case "${option}" in h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 local response response=$(aws ec2 describe-key-pairs \ --query 'KeyPairs[*].[KeyName, KeyFingerprint]' \ --output text) || { aws_cli_error_log ${?} errecho "ERROR: AWS reports describe-key-pairs operation failed.$response" return 1 } echo "$response" return 0 }

Le funzioni di utilità utilizzate in questo esempio.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
C++
SDKper C++
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

//! Describe all Amazon Elastic Compute Cloud (Amazon EC2) instance key pairs. /*! \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::EC2::describeKeyPairs( const Aws::Client::ClientConfiguration &clientConfiguration) { 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; } return outcome.IsSuccess(); }
CLI
AWS CLI

Per visualizzare una coppia di chiavi

Nell'esempio di describe-key-pairs seguente vengono visualizzate informazioni sulla coppia di chiavi specificata.

aws ec2 describe-key-pairs \ --key-names my-key-pair

Output:

{ "KeyPairs": [ { "KeyPairId": "key-0b94643da6EXAMPLE", "KeyFingerprint": "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f", "KeyName": "my-key-pair", "KeyType": "rsa", "Tags": [], "CreateTime": "2022-05-27T21:51:16.000Z" } ] }

Per ulteriori informazioni, consulta Descrivi le chiavi pubbliche nella Amazon EC2 User Guide.

Java
SDKper Java 2.x
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/** * Asynchronously describes the key pairs associated with the current AWS account. * * @return a {@link CompletableFuture} containing the {@link DescribeKeyPairsResponse} object, which provides * information about the key pairs. */ public CompletableFuture<DescribeKeyPairsResponse> describeKeysAsync() { CompletableFuture<DescribeKeyPairsResponse> responseFuture = getAsyncClient().describeKeyPairs(); responseFuture.whenComplete((response, exception) -> { if (exception != null) { throw new RuntimeException("Failed to describe key pairs: " + exception.getMessage(), exception); } }); return responseFuture; }
JavaScript
SDKper JavaScript (v3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

import { DescribeKeyPairsCommand, EC2Client } from "@aws-sdk/client-ec2"; /** * List all key pairs in the current AWS account. * @param {{ dryRun: boolean }} */ export const main = async ({ dryRun }) => { const client = new EC2Client({}); const command = new DescribeKeyPairsCommand({ DryRun: dryRun }); try { const { KeyPairs } = await client.send(command); const keyPairList = KeyPairs.map( (kp) => ` • ${kp.KeyPairId}: ${kp.KeyName}`, ).join("\n"); console.log("The following key pairs were found in your account:"); console.log(keyPairList); } catch (caught) { if (caught instanceof Error && caught.name === "DryRunOperation") { console.log(`${caught.message}`); } else { throw caught; } } };
Kotlin
SDKper Kotlin
Nota

c'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

suspend fun describeEC2Keys() { Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.describeKeyPairs(DescribeKeyPairsRequest {}) response.keyPairs?.forEach { keyPair -> println("Found key pair with name ${keyPair.keyName} and fingerprint ${ keyPair.keyFingerprint}") } } }
PowerShell
Strumenti per PowerShell

Esempio 1: Questo esempio descrive la coppia di key pair specificata.

Get-EC2KeyPair -KeyName my-key-pair

Output:

KeyFingerprint KeyName -------------- ------- 1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f my-key-pair

Esempio 2: questo esempio descrive tutte le coppie di chiavi.

Get-EC2KeyPair
  • Per API i dettagli, vedere DescribeKeyPairsin AWS Tools for PowerShell Cmdlet Reference.

Python
SDKper Python (Boto3)
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

class KeyPairWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions.""" def __init__(self, ec2_resource, key_file_dir, key_pair=None): """ :param ec2_resource: A Boto3 Amazon EC2 resource. This high-level resource is used to create additional high-level objects that wrap low-level Amazon EC2 service actions. :param key_file_dir: The folder where the private key information is stored. This should be a secure folder. :param key_pair: A Boto3 KeyPair object. This is a high-level object that wraps key pair actions. """ self.ec2_resource = ec2_resource self.key_pair = key_pair self.key_file_path = None self.key_file_dir = key_file_dir @classmethod def from_resource(cls): ec2_resource = boto3.resource("ec2") return cls(ec2_resource, tempfile.TemporaryDirectory()) def list(self, limit): """ Displays a list of key pairs for the current account. :param limit: The maximum number of key pairs to list. """ try: for kp in self.ec2_resource.key_pairs.limit(limit): print(f"Found {kp.key_type} key {kp.name} with fingerprint:") print(f"\t{kp.key_fingerprint}") except ClientError as err: logger.error( "Couldn't list key pairs. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • Per API i dettagli, vedere DescribeKeyPairsPython (Boto3) Reference.AWS SDK API

Rust
SDKper Rust
Nota

c'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

pub async fn list_key_pair(&self) -> Result<Vec<KeyPairInfo>, EC2Error> { let output = self.client.describe_key_pairs().send().await?; Ok(output.key_pairs.unwrap_or_default()) }
SAP ABAP
SDKper SAP ABAP
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

TRY. oo_result = lo_ec2->describekeypairs( ) . " oo_result is returned for testing purposes. " DATA(lt_key_pairs) = oo_result->get_keypairs( ). MESSAGE 'Retrieved information about key pairs.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY.