Sélectionner vos préférences de cookies

Nous utilisons des cookies essentiels et des outils similaires qui sont nécessaires au fonctionnement de notre site et à la fourniture de nos services. Nous utilisons des cookies de performance pour collecter des statistiques anonymes afin de comprendre comment les clients utilisent notre site et d’apporter des améliorations. Les cookies essentiels ne peuvent pas être désactivés, mais vous pouvez cliquer sur « Personnaliser » ou « Refuser » pour refuser les cookies de performance.

Si vous êtes d’accord, AWS et les tiers approuvés utiliseront également des cookies pour fournir des fonctionnalités utiles au site, mémoriser vos préférences et afficher du contenu pertinent, y compris des publicités pertinentes. Pour accepter ou refuser tous les cookies non essentiels, cliquez sur « Accepter » ou « Refuser ». Pour effectuer des choix plus détaillés, cliquez sur « Personnaliser ».

Mise à jour des groupes de sécurité - AWS SDK for .NET (version 3)

La version 4 (V4) du AWS SDK for .NET est en avant-première ! Pour obtenir des informations sur cette nouvelle version en avant-première, consultez le guide du développeur AWS SDK for .NET (version 4).

Veuillez noter que la version V4 du SDK est en cours de prévisualisation, son contenu est donc sujet à modification.

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

La version 4 (V4) du AWS SDK for .NET est en avant-première ! Pour obtenir des informations sur cette nouvelle version en avant-première, consultez le guide du développeur AWS SDK for .NET (version 4).

Veuillez noter que la version V4 du SDK est en cours de prévisualisation, son contenu est donc sujet à modification.

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Mise à jour des groupes de sécurité

Cet exemple montre comment utiliser le pour AWS SDK for .NET ajouter une règle à un groupe de sécurité. En particulier, l'exemple ajoute une règle pour autoriser le trafic entrant sur un port TCP donné, qui peut être utilisée, par exemple, pour les connexions à distance à une EC2 instance. L'application prend l'identifiant d'un groupe de sécurité existant, une adresse IP (ou plage d'adresses) au format CIDR et éventuellement un numéro de port TCP. Il ajoute ensuite une règle entrante au groupe de sécurité donné.

Note

Pour utiliser cet exemple, vous avez besoin d'une adresse IP (ou d'une plage d'adresses) au format CIDR. Consultez la section Considérations supplémentaires à la fin de cette rubrique pour connaître les méthodes permettant d'obtenir l'adresse IP de votre ordinateur local.

Les sections suivantes fournissent des extraits de cet exemple. Le code complet de l'exemple est affiché ensuite et peut être créé et exécuté tel quel.

Ajouter une règle de trafic entrant

L'extrait suivant ajoute une règle entrante à un groupe de sécurité pour une adresse IP (ou plage) et un port TCP particuliers.

L'exemple à la fin de cette rubrique montre cet extrait de code en cours d'utilisation.

// // Method that adds a TCP ingress rule to a security group private static async Task AddIngressRule( IAmazonEC2 eC2Client, string groupID, string ipAddress, int port) { // Create an object to hold the request information for the rule. // It uses an IpPermission object to hold the IP information for the rule. var ingressRequest = new AuthorizeSecurityGroupIngressRequest{ GroupId = groupID}; ingressRequest.IpPermissions.Add(new IpPermission{ IpProtocol = "tcp", FromPort = port, ToPort = port, Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } } }); // Create the inbound rule for the security group AuthorizeSecurityGroupIngressResponse responseIngress = await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest); Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}."); Console.WriteLine($"Result: {responseIngress.HttpStatusCode}"); }

Code complet

Cette section présente les références pertinentes et le code complet de cet exemple.

NuGet colis :

Éléments de programmation :

NuGet colis :

Éléments de programmation :

using System; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.EC2; using Amazon.EC2.Model; namespace EC2AddRuleForRDP { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to add a rule that allows inbound traffic on TCP a port class Program { private const int DefaultPort = 3389; static async Task Main(string[] args) { // Parse the command line and show help if necessary var parsedArgs = CommandLine.Parse(args); if(parsedArgs.Count == 0) { PrintHelp(); return; } // Get the application arguments from the parsed list var groupID = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-id"); var ipAddress = CommandLine.GetArgument(parsedArgs, null, "-i", "--ip-address"); var portStr = CommandLine.GetArgument(parsedArgs, DefaultPort.ToString(), "-p", "--port"); if(string.IsNullOrEmpty(ipAddress)) CommandLine.ErrorExit("\nYou must supply an IP address in CIDR format."); if(string.IsNullOrEmpty(groupID) || !groupID.StartsWith("sg-")) CommandLine.ErrorExit("\nThe ID for a security group is missing or incorrect."); if(int.Parse(portStr) == 0) CommandLine.ErrorExit($"\nThe given TCP port number, {portStr}, isn't allowed."); // Add a rule to the given security group that allows // inbound traffic on a TCP port await AddIngressRule( new AmazonEC2Client(), groupID, ipAddress, int.Parse(portStr)); } // // Method that adds a TCP ingress rule to a security group private static async Task AddIngressRule( IAmazonEC2 eC2Client, string groupID, string ipAddress, int port) { // Create an object to hold the request information for the rule. // It uses an IpPermission object to hold the IP information for the rule. var ingressRequest = new AuthorizeSecurityGroupIngressRequest{ GroupId = groupID}; ingressRequest.IpPermissions.Add(new IpPermission{ IpProtocol = "tcp", FromPort = port, ToPort = port, Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } } }); // Create the inbound rule for the security group AuthorizeSecurityGroupIngressResponse responseIngress = await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest); Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}."); Console.WriteLine($"Result: {responseIngress.HttpStatusCode}"); } // // Command-line help private static void PrintHelp() { Console.WriteLine( "\nUsage: EC2AddRuleForRDP -g <group-id> -i <ip-address> [-p <port>]" + "\n -g, --group-id: The ID of the security group to which you want to add the inbound rule." + "\n -i, --ip-address: An IP address or address range in CIDR format." + "\n -p, --port: The TCP port number. Defaults to 3389."); } } // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class that represents a command line on the console or terminal. // (This is the same for all examples. When you have seen it once, you can ignore it.) static class CommandLine { // // Method to parse a command line of the form: "--key value" or "-k value". // // Parameters: // - args: The command-line arguments passed into the application by the system. // // Returns: // A Dictionary with string Keys and Values. // // If a key is found without a matching value, Dictionary.Value is set to the key // (including the dashes). // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN", // where "N" represents sequential numbers. public static Dictionary<string,string> Parse(string[] args) { var parsedArgs = new Dictionary<string,string>(); int i = 0, n = 0; while(i < args.Length) { // If the first argument in this iteration starts with a dash it's an option. if(args[i].StartsWith("-")) { var key = args[i++]; var value = key; // Check to see if there's a value that goes with this option? if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++]; parsedArgs.Add(key, value); } // If the first argument in this iteration doesn't start with a dash, it's a value else { parsedArgs.Add("--NoKey" + n.ToString(), args[i++]); n++; } } return parsedArgs; } // // Method to get an argument from the parsed command-line arguments // // Parameters: // - parsedArgs: The Dictionary object returned from the Parse() method (shown above). // - defaultValue: The default string to return if the specified key isn't in parsedArgs. // - keys: An array of keys to look for in parsedArgs. public static string GetArgument( Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys) { string retval = null; foreach(var key in keys) if(parsedArgs.TryGetValue(key, out retval)) break; return retval ?? defaultReturn; } // // Method to exit the application with an error. public static void ErrorExit(string msg, int code=1) { Console.WriteLine("\nError"); Console.WriteLine(msg); Environment.Exit(code); } } }

using System; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.EC2; using Amazon.EC2.Model; namespace EC2AddRuleForRDP { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to add a rule that allows inbound traffic on TCP a port class Program { private const int DefaultPort = 3389; static async Task Main(string[] args) { // Parse the command line and show help if necessary var parsedArgs = CommandLine.Parse(args); if(parsedArgs.Count == 0) { PrintHelp(); return; } // Get the application arguments from the parsed list var groupID = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-id"); var ipAddress = CommandLine.GetArgument(parsedArgs, null, "-i", "--ip-address"); var portStr = CommandLine.GetArgument(parsedArgs, DefaultPort.ToString(), "-p", "--port"); if(string.IsNullOrEmpty(ipAddress)) CommandLine.ErrorExit("\nYou must supply an IP address in CIDR format."); if(string.IsNullOrEmpty(groupID) || !groupID.StartsWith("sg-")) CommandLine.ErrorExit("\nThe ID for a security group is missing or incorrect."); if(int.Parse(portStr) == 0) CommandLine.ErrorExit($"\nThe given TCP port number, {portStr}, isn't allowed."); // Add a rule to the given security group that allows // inbound traffic on a TCP port await AddIngressRule( new AmazonEC2Client(), groupID, ipAddress, int.Parse(portStr)); } // // Method that adds a TCP ingress rule to a security group private static async Task AddIngressRule( IAmazonEC2 eC2Client, string groupID, string ipAddress, int port) { // Create an object to hold the request information for the rule. // It uses an IpPermission object to hold the IP information for the rule. var ingressRequest = new AuthorizeSecurityGroupIngressRequest{ GroupId = groupID}; ingressRequest.IpPermissions.Add(new IpPermission{ IpProtocol = "tcp", FromPort = port, ToPort = port, Ipv4Ranges = new List<IpRange>() { new IpRange { CidrIp = ipAddress } } }); // Create the inbound rule for the security group AuthorizeSecurityGroupIngressResponse responseIngress = await eC2Client.AuthorizeSecurityGroupIngressAsync(ingressRequest); Console.WriteLine($"\nNew RDP rule was written in {groupID} for {ipAddress}."); Console.WriteLine($"Result: {responseIngress.HttpStatusCode}"); } // // Command-line help private static void PrintHelp() { Console.WriteLine( "\nUsage: EC2AddRuleForRDP -g <group-id> -i <ip-address> [-p <port>]" + "\n -g, --group-id: The ID of the security group to which you want to add the inbound rule." + "\n -i, --ip-address: An IP address or address range in CIDR format." + "\n -p, --port: The TCP port number. Defaults to 3389."); } } // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class that represents a command line on the console or terminal. // (This is the same for all examples. When you have seen it once, you can ignore it.) static class CommandLine { // // Method to parse a command line of the form: "--key value" or "-k value". // // Parameters: // - args: The command-line arguments passed into the application by the system. // // Returns: // A Dictionary with string Keys and Values. // // If a key is found without a matching value, Dictionary.Value is set to the key // (including the dashes). // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN", // where "N" represents sequential numbers. public static Dictionary<string,string> Parse(string[] args) { var parsedArgs = new Dictionary<string,string>(); int i = 0, n = 0; while(i < args.Length) { // If the first argument in this iteration starts with a dash it's an option. if(args[i].StartsWith("-")) { var key = args[i++]; var value = key; // Check to see if there's a value that goes with this option? if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++]; parsedArgs.Add(key, value); } // If the first argument in this iteration doesn't start with a dash, it's a value else { parsedArgs.Add("--NoKey" + n.ToString(), args[i++]); n++; } } return parsedArgs; } // // Method to get an argument from the parsed command-line arguments // // Parameters: // - parsedArgs: The Dictionary object returned from the Parse() method (shown above). // - defaultValue: The default string to return if the specified key isn't in parsedArgs. // - keys: An array of keys to look for in parsedArgs. public static string GetArgument( Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys) { string retval = null; foreach(var key in keys) if(parsedArgs.TryGetValue(key, out retval)) break; return retval ?? defaultReturn; } // // Method to exit the application with an error. public static void ErrorExit(string msg, int code=1) { Console.WriteLine("\nError"); Console.WriteLine(msg); Environment.Exit(code); } } }

Considérations supplémentaires

  • Si vous ne fournissez pas de numéro de port, l'application utilise par défaut le port 3389. Il s'agit du port pour Windows RDP, qui vous permet de vous connecter à une EC2 instance exécutant Windows. Si vous lancez une EC2 instance exécutant Linux, vous pouvez utiliser le port TCP 22 (SSH) à la place.

  • Notez que l'exemple prend la valeur IpProtocol « tcp ». Les valeurs de se IpProtocol trouvent dans la description de la IpProtocol propriété de la IpPermissionclasse.

  • Vous aurez peut-être besoin de l'adresse IP de votre ordinateur local lorsque vous utiliserez cet exemple. Voici certains des moyens par lesquels vous pouvez obtenir l'adresse.

    • Si votre ordinateur local (à partir duquel vous allez vous connecter à votre EC2 instance) possède une adresse IP publique statique, vous pouvez utiliser un service pour obtenir cette adresse. L'un de ces services est http://checkip.amazonaws.com/. Pour en savoir plus sur l'autorisation du trafic entrant, consultez les sections Ajouter des règles à un groupe de sécurité et Règles de groupe de sécurité pour différents cas d'utilisation dans le guide de EC2 l'utilisateur Amazon.

    • Une autre méthode pour obtenir l'adresse IP de votre ordinateur local consiste à utiliser la EC2 console Amazon.

      Sélectionnez l'un de vos groupes de sécurité, sélectionnez l'onglet Règles entrantes, puis choisissez Modifier les règles entrantes. Dans une règle entrante, ouvrez le menu déroulant dans la colonne Source et choisissez Mon adresse IP pour voir l'adresse IP de votre ordinateur local au format CIDR. Assurez-vous d'annuler l'opération.

  • Vous pouvez vérifier les résultats de cet exemple en examinant la liste des groupes de sécurité dans la EC2console Amazon.

Rubrique suivante :

Paires de clés

Rubrique précédente :

Création de groupes de sécurité
ConfidentialitéConditions d'utilisation du sitePréférences de cookies
© 2025, Amazon Web Services, Inc. ou ses affiliés. Tous droits réservés.