

Version 4 (V4) von AWS SDK für .NET wurde veröffentlicht\$1

Informationen zu wichtigen Änderungen und zur Migration Ihrer Anwendungen finden Sie im [Migrationsthema](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html).

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Arbeiten mit Sicherheitsgruppen in Amazon EC2
<a name="security-groups"></a>

In Amazon EC2 fungiert eine *Sicherheitsgruppe* als virtuelle Firewall, die den Netzwerkverkehr für eine oder mehrere EC2-Instances steuert. Standardmäßig ordnet EC2 Ihre Instances einer Sicherheitsgruppe zu, die keinen eingehenden Datenverkehr zulässt. Sie können eine Sicherheitsgruppe erstellen, die es den EC2-Instances ermöglicht, eingehenden Datenverkehr zu akzeptieren. Wenn Sie beispielsweise eine Verbindung zu einer EC2 Windows-Instance herstellen müssen, muss die Sicherheitsgruppe so konfiguriert werden, dass RDP-Datenverkehr möglich ist.

Weitere Informationen zu Sicherheitsgruppen finden Sie unter [Amazon EC2-Sicherheitsgruppen](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html) im [Amazon EC2 EC2-Benutzerhandbuch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

**Warnung**  
EC2-Classic wurde am 15. August 2022 außer Betrieb genommen. Wir empfehlen Ihnen die Migration von EC2-Classic zu einer VPC. Weitere Informationen finden Sie im Blogbeitrag [EC2-Classic Networking is Retiring — So](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/) bereiten Sie sich vor.

Informationen zu den Voraussetzungen APIs und Voraussetzungen finden Sie im übergeordneten Abschnitt (). [Arbeiten mit Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [Auflisten von Sicherheitsgruppen](enumerate-security-groups.md)
+ [Erstellen von Sicherheitsgruppen](creating-security-group.md)
+ [Sicherheitsgruppen werden aktualisiert](authorize-ingress.md)

# Auflisten von Sicherheitsgruppen
<a name="enumerate-security-groups"></a>

Dieses Beispiel zeigt Ihnen, wie Sie die verwenden, AWS SDK für .NET um Sicherheitsgruppen aufzulisten. Wenn Sie eine [Amazon Virtual Private Cloud Cloud-ID angeben](https://docs.aws.amazon.com/vpc/latest/userguide/), listet die Anwendung die Sicherheitsgruppen für diese bestimmte VPC auf. Andernfalls zeigt die Anwendung einfach eine Liste aller verfügbaren Sicherheitsgruppen an.

Die folgenden Abschnitte enthalten Auszüge aus diesem Beispiel. Der [vollständige Code für das Beispiel](#enum-sec-groups-complete-code) wird danach angezeigt und kann unverändert erstellt und ausgeführt werden.

**Topics**
+ [Zählen Sie Sicherheitsgruppen auf](#enum-sec-groups-enum)
+ [Vollständiger Code](#enum-sec-groups-complete-code)
+ [Weitere Überlegungen](#enum-sec-groups-additional)

## Zählen Sie Sicherheitsgruppen auf
<a name="enum-sec-groups-enum"></a>

Der folgende Ausschnitt listet Ihre Sicherheitsgruppen auf. Es listet alle Gruppen oder die Gruppen für eine bestimmte VPC auf, falls eine angegeben ist.

Das Beispiel [am Ende dieses Themas zeigt, wie dieser](#enum-sec-groups-complete-code) Codeausschnitt verwendet wird.

```
    //
    // Method to enumerate the security groups
    private static async Task EnumerateGroups(IAmazonEC2 ec2Client, string vpcID)
    {
      // A request object, in case we need it.
      var request = new DescribeSecurityGroupsRequest();

      // Put together the properties, if needed
      if(!string.IsNullOrEmpty(vpcID))
      {
        // We have a VPC ID. Find the security groups for just that VPC.
        Console.WriteLine($"\nGetting security groups for VPC {vpcID}...\n");
        request.Filters.Add(new Filter
        {
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });
      }

      // Get the list of security groups
      DescribeSecurityGroupsResponse response =
        await ec2Client.DescribeSecurityGroupsAsync(request);

      // Display the list of security groups.
      foreach (SecurityGroup item in response.SecurityGroups)
      {
        Console.WriteLine("Security group: " + item.GroupId);
        Console.WriteLine("\tGroupId: " + item.GroupId);
        Console.WriteLine("\tGroupName: " + item.GroupName);
        Console.WriteLine("\tVpcId: " + item.VpcId);
        Console.WriteLine();
      }
    }
```

## Vollständiger Code
<a name="enum-sec-groups-complete-code"></a>

Dieser Abschnitt enthält relevante Referenzen und den vollständigen Code für dieses Beispiel.

### SDK-Referenzen
<a name="w2aac19c15c21c13c13c15b5b1"></a>

NuGet Pakete:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemente der Programmierung:
+ [Namespace Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Klasse [EC2Amazon-Kunde](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

  Klasse [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)

  Klasse [DescribeSecurityGroupsResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeSecurityGroupsResponse.html)

  [Klassenfilter](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TFilter.html)

  Klasse [SecurityGroup](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TSecurityGroup.html)

### Der Kodex
<a name="w2aac19c15c21c13c13c15b7b1"></a>

```
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.EC2;
using Amazon.EC2.Model;

namespace EC2EnumerateSecGroups
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Parse the command line
       string vpcID = string.Empty;
      if(args.Length == 0)
      {
        Console.WriteLine("\nEC2EnumerateSecGroups [vpc_id]");
        Console.WriteLine("  vpc_id - The ID of the VPC for which you want to see security groups.");
        Console.WriteLine("\nSince you specified no arguments, showing all available security groups.");
      }
      else
      {
        vpcID = args[0];
      }

      if(vpcID.StartsWith("vpc-") || string.IsNullOrEmpty(vpcID))
      {
        // Create an EC2 client object
        var ec2Client = new AmazonEC2Client();

        // Enumerate the security groups
        await EnumerateGroups(ec2Client, vpcID);
      }
      else
      {
        Console.WriteLine("Could not find a valid VPC ID in the command-line arguments:");
        Console.WriteLine($"{args[0]}");
      }
    }


    //
    // Method to enumerate the security groups
    private static async Task EnumerateGroups(IAmazonEC2 ec2Client, string vpcID)
    {
      // A request object, in case we need it.
      var request = new DescribeSecurityGroupsRequest();

      // Put together the properties, if needed
      if(!string.IsNullOrEmpty(vpcID))
      {
        // We have a VPC ID. Find the security groups for just that VPC.
        Console.WriteLine($"\nGetting security groups for VPC {vpcID}...\n");
        request.Filters.Add(new Filter
        {
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });
      }

      // Get the list of security groups
      DescribeSecurityGroupsResponse response =
        await ec2Client.DescribeSecurityGroupsAsync(request);

      // Display the list of security groups.
      foreach (SecurityGroup item in response.SecurityGroups)
      {
        Console.WriteLine("Security group: " + item.GroupId);
        Console.WriteLine("\tGroupId: " + item.GroupId);
        Console.WriteLine("\tGroupName: " + item.GroupName);
        Console.WriteLine("\tVpcId: " + item.VpcId);
        Console.WriteLine();
      }
    }
  }
}
```

## Weitere Überlegungen
<a name="enum-sec-groups-additional"></a>
+ Beachten Sie für den VPC-Fall, dass der Filter so konstruiert ist, dass der `Name` Teil des Name-Wert-Paares auf „vpc-id“ gesetzt ist. Dieser Name stammt aus der Beschreibung der Eigenschaft der `Filters` Klasse. [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)
+ Um die vollständige Liste Ihrer Sicherheitsgruppen zu erhalten, können Sie diese auch [ DescribeSecurityGroupsAsync ohne Parameter](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/MEC2DescribeSecurityGroupsAsyncCancellationToken.html) verwenden.
+ Sie können die Ergebnisse überprüfen, indem Sie die Liste der Sicherheitsgruppen in der [Amazon EC2 EC2-Konsole](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups) überprüfen.

# Erstellen von Sicherheitsgruppen
<a name="creating-security-group"></a>

Dieses Beispiel zeigt Ihnen, wie Sie mit AWS SDK für .NET dem eine Sicherheitsgruppe erstellen. Sie können die ID einer vorhandenen VPC angeben, um eine Sicherheitsgruppe für EC2 in einer VPC zu erstellen. Wenn Sie keine solche ID angeben, gilt die neue Sicherheitsgruppe für EC2-Classic, sofern Ihr Konto dies unterstützt. AWS 

Wenn Sie keine VPC-ID angeben und Ihr AWS Konto EC2-Classic nicht unterstützt, gehört die neue Sicherheitsgruppe zur Standard-VPC Ihres Kontos.

**Warnung**  
EC2-Classic wurde am 15. August 2022 außer Betrieb genommen. Wir empfehlen Ihnen die Migration von EC2-Classic zu einer VPC. Weitere Informationen finden Sie im Blogbeitrag [EC2-Classic Networking is Retiring](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/) — So bereiten Sie sich vor.

Die folgenden Abschnitte enthalten Auszüge aus diesem Beispiel. Der [vollständige Code für das Beispiel](#create-sec-groups-complete-code) wird danach angezeigt und kann unverändert erstellt und ausgeführt werden.

**Topics**
+ [Suchen Sie nach vorhandenen Sicherheitsgruppen](#create-sec-groups-find)
+ [Eine Sicherheitsgruppe erstellen](#create-sec-groups-enum)
+ [Vollständiger Code](#create-sec-groups-complete-code)

## Suchen Sie nach vorhandenen Sicherheitsgruppen
<a name="create-sec-groups-find"></a>

Das folgende Snippet sucht nach vorhandenen Sicherheitsgruppen mit dem angegebenen Namen in der angegebenen VPC.

Das Beispiel [am Ende dieses Themas zeigt, wie dieses](#create-sec-groups-complete-code) Snippet verwendet wird.

```
    //
    // Method to determine if a security group with the specified name
    // already exists in the VPC
    private static async Task<List<SecurityGroup>> FindSecurityGroups(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      var request = new DescribeSecurityGroupsRequest();
      request.Filters.Add(new Filter{
        Name = "group-name",
        Values = new List<string>() { groupName }
      });
      if(!string.IsNullOrEmpty(vpcID))
        request.Filters.Add(new Filter{
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });

      var response = await ec2Client.DescribeSecurityGroupsAsync(request);
      return response.SecurityGroups;
    }
```

## Eine Sicherheitsgruppe erstellen
<a name="create-sec-groups-enum"></a>

Das folgende Snippet erstellt eine neue Sicherheitsgruppe, wenn eine Gruppe mit diesem Namen in der angegebenen VPC nicht existiert. Wenn keine VPC angegeben ist und eine oder mehrere Gruppen mit diesem Namen existieren, gibt das Snippet einfach die Liste der Gruppen zurück.

Das Beispiel [am Ende dieses Themas zeigt, wie dieses](#create-sec-groups-complete-code) Snippet verwendet wird.

```
    //
    // Method to create a new security group (either EC2-Classic or EC2-VPC)
    // If vpcID is empty, the security group will be for EC2-Classic
    private static async Task<List<SecurityGroup>> CreateSecurityGroup(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      // See if one or more security groups with that name
      // already exist in the given VPC. If so, return the list of them.
      var securityGroups = await FindSecurityGroups(ec2Client, groupName, vpcID);
      if (securityGroups.Count > 0)
      {
        Console.WriteLine(
          $"\nOne or more security groups with name {groupName} already exist.\n");
        return securityGroups;
      }

      // If the security group doesn't already exists, create it.
      var createRequest = new CreateSecurityGroupRequest{
        GroupName = groupName
      };
      if(string.IsNullOrEmpty(vpcID))
      {
        createRequest.Description = "My .NET example security group for EC2-Classic";
      }
      else
      {
        createRequest.VpcId = vpcID;
        createRequest.Description = "My .NET example security group for EC2-VPC";
      }
      CreateSecurityGroupResponse createResponse =
        await ec2Client.CreateSecurityGroupAsync(createRequest);

      // Return the new security group
      DescribeSecurityGroupsResponse describeResponse =
        await ec2Client.DescribeSecurityGroupsAsync(new DescribeSecurityGroupsRequest{
          GroupIds = new List<string>() { createResponse.GroupId }
        });
      return describeResponse.SecurityGroups;
    }
```

## Vollständiger Code
<a name="create-sec-groups-complete-code"></a>

Dieser Abschnitt enthält relevante Referenzen und den vollständigen Code für dieses Beispiel.

### SDK-Referenzen
<a name="w2aac19c15c21c13c15c23b5b1"></a>

NuGet Pakete:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemente der Programmierung:
+ [Namespace Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Klasse [EC2Amazon-Kunde](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

  Klasse [CreateSecurityGroupRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TCreateSecurityGroupRequest.html)

  Klasse [CreateSecurityGroupResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TCreateSecurityGroupResponse.html)

  Klasse [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeSecurityGroupsRequest.html)

  Klasse [DescribeSecurityGroupsResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeSecurityGroupsResponse.html)

  [Klassenfilter](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TFilter.html)

  Klasse [SecurityGroup](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TSecurityGroup.html)

### Der Code
<a name="w2aac19c15c21c13c15c23b7b1"></a>

```
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.EC2;
using Amazon.EC2.Model;

namespace EC2CreateSecGroup
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create a security group
  class Program
  {
    private const int MaxArgs = 2;

    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;
      }
      if(parsedArgs.Count > MaxArgs)
        CommandLine.ErrorExit("\nThe number of command-line arguments is incorrect." +
          "\nRun the command with no arguments to see help.");

      // Get the application arguments from the parsed list
      var groupName = CommandLine.GetArgument(parsedArgs, null, "-g", "--group-name");
      var vpcID = CommandLine.GetArgument(parsedArgs, null, "-v", "--vpc-id");
      if(string.IsNullOrEmpty(groupName))
        CommandLine.ErrorExit("\nYou must supply a name for the new group." +
          "\nRun the command with no arguments to see help.");
      if(!string.IsNullOrEmpty(vpcID) && !vpcID.StartsWith("vpc-"))
        CommandLine.ErrorExit($"\nNot a valid VPC ID: {vpcID}");

      // groupName has a value and vpcID either has a value or is null (which is fine)
      // Create the new security group and display information about it
      var securityGroups =
        await CreateSecurityGroup(new AmazonEC2Client(), groupName, vpcID);
      Console.WriteLine("Information about the security group(s):");
      foreach(var group in securityGroups)
      {
        Console.WriteLine($"\nGroupName: {group.GroupName}");
        Console.WriteLine($"GroupId: {group.GroupId}");
        Console.WriteLine($"Description: {group.Description}");
        Console.WriteLine($"VpcId (if any): {group.VpcId}");
      }
    }


    //
    // Method to create a new security group (either EC2-Classic or EC2-VPC)
    // If vpcID is empty, the security group will be for EC2-Classic
    private static async Task<List<SecurityGroup>> CreateSecurityGroup(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      // See if one or more security groups with that name
      // already exist in the given VPC. If so, return the list of them.
      var securityGroups = await FindSecurityGroups(ec2Client, groupName, vpcID);
      if (securityGroups.Count > 0)
      {
        Console.WriteLine(
          $"\nOne or more security groups with name {groupName} already exist.\n");
        return securityGroups;
      }

      // If the security group doesn't already exists, create it.
      var createRequest = new CreateSecurityGroupRequest{
        GroupName = groupName
      };
      if(string.IsNullOrEmpty(vpcID))
      {
        createRequest.Description = "Security group for .NET code example (no VPC specified)";
      }
      else
      {
        createRequest.VpcId = vpcID;
        createRequest.Description = "Security group for .NET code example (VPC: " + vpcID + ")";
      }
      CreateSecurityGroupResponse createResponse =
        await ec2Client.CreateSecurityGroupAsync(createRequest);

      // Return the new security group
      DescribeSecurityGroupsResponse describeResponse =
        await ec2Client.DescribeSecurityGroupsAsync(new DescribeSecurityGroupsRequest{
          GroupIds = new List<string>() { createResponse.GroupId }
        });
      return describeResponse.SecurityGroups;
    }


    //
    // Method to determine if a security group with the specified name
    // already exists in the VPC
    private static async Task<List<SecurityGroup>> FindSecurityGroups(
      IAmazonEC2 ec2Client, string groupName, string vpcID)
    {
      var request = new DescribeSecurityGroupsRequest();
      request.Filters.Add(new Filter{
        Name = "group-name",
        Values = new List<string>() { groupName }
      });
      if(!string.IsNullOrEmpty(vpcID))
        request.Filters.Add(new Filter{
          Name = "vpc-id",
          Values = new List<string>() { vpcID }
        });

      var response = await ec2Client.DescribeSecurityGroupsAsync(request);
      return response.SecurityGroups;
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2CreateSecGroup -g <group-name> [-v <vpc-id>]" +
        "\n  -g, --group-name: The name you would like the new security group to have." +
        "\n  -v, --vpc-id: The ID of a VPC to which the new security group will belong." +
        "\n     If vpc-id isn't present, the security group will be" +
        "\n     for EC2-Classic (if your AWS account supports this)" +
        "\n     or will use the default VCP for EC2-VPC.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // 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);
    }
  }

}
```

# Sicherheitsgruppen werden aktualisiert
<a name="authorize-ingress"></a>

Dieses Beispiel zeigt Ihnen, wie Sie AWS SDK für .NET mit dem einer Sicherheitsgruppe eine Regel hinzufügen können. Insbesondere fügt das Beispiel eine Regel hinzu, die eingehenden Datenverkehr an einem bestimmten TCP-Port zulässt, was beispielsweise für Remoteverbindungen zu einer EC2-Instance verwendet werden kann. Die Anwendung verwendet die ID einer vorhandenen Sicherheitsgruppe, eine IP-Adresse (oder einen Adressbereich) im CIDR-Format und optional eine TCP-Portnummer. Anschließend fügt sie der angegebenen Sicherheitsgruppe eine Regel für eingehenden Datenverkehr hinzu.

**Anmerkung**  
Um dieses Beispiel verwenden zu können, benötigen Sie eine IP-Adresse (oder einen Adressbereich) im CIDR-Format. Methoden zum Abrufen der IP-Adresse Ihres lokalen Computers finden Sie unter **Zusätzliche Überlegungen** am Ende dieses Themas.

Die folgenden Abschnitte enthalten Auszüge aus diesem Beispiel. Der [vollständige Code für das Beispiel](#authorize-ingress-complete-code) wird danach angezeigt und kann unverändert erstellt und ausgeführt werden.

**Topics**
+ [Fügen Sie eine Regel für eingehenden Datenverkehr hinzu](#authorize-ingress-add-rule)
+ [Vollständiger Code](#authorize-ingress-complete-code)
+ [Weitere Überlegungen](#authorize-ingress-additional)

## Fügen Sie eine Regel für eingehenden Datenverkehr hinzu
<a name="authorize-ingress-add-rule"></a>

Das folgende Snippet fügt einer Sicherheitsgruppe eine Regel für eingehenden Datenverkehr für eine bestimmte IP-Adresse (oder einen bestimmten Bereich) und einen bestimmten TCP-Port hinzu.

Das Beispiel [am Ende dieses Themas zeigt, wie dieser](#authorize-ingress-complete-code) Codeausschnitt verwendet wird.

```
    //
    // 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}");
    }
```

## Vollständiger Code
<a name="authorize-ingress-complete-code"></a>

Dieser Abschnitt enthält relevante Referenzen und den vollständigen Code für dieses Beispiel.

### SDK-Referenzen
<a name="w2aac19c15c21c13c17c17b5b1"></a>

NuGet Pakete:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemente der Programmierung:
+ [Namespace Amazon.ec2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  Klasse [EC2Amazon-Kunde](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

  Klasse [AuthorizeSecurityGroupIngressRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TAuthorizeSecurityGroupIngressRequest.html)

  Klasse [AuthorizeSecurityGroupIngressResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TAuthorizeSecurityGroupIngressResponse.html)

  Klasse [IpPermission](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TIpPermission.html)

  Klasse [IpRange](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TIpRange.html)

### Der Code
<a name="w2aac19c15c21c13c17c17b7b1"></a>

```
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);
    }
  }

}
```

## Weitere Überlegungen
<a name="authorize-ingress-additional"></a>
+ Wenn Sie keine Portnummer angeben, verwendet die Anwendung standardmäßig Port 3389. Dies ist der Port für Windows RDP, über den Sie eine Verbindung zu einer EC2-Instance herstellen können, auf der Windows ausgeführt wird. Wenn Sie eine EC2-Instance starten, auf der Linux ausgeführt wird, können Sie stattdessen TCP-Port 22 (SSH) verwenden.
+ Beachten Sie, dass das Beispiel `IpProtocol` auf „tcp“ gesetzt ist. Die Werte für `IpProtocol` finden Sie in der Beschreibung der `IpProtocol` Eigenschaft der [IpPermission](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TIpPermission.html)Klasse.
+ Wenn Sie dieses Beispiel verwenden, benötigen Sie möglicherweise die IP-Adresse Ihres lokalen Computers. Im Folgenden sind einige Möglichkeiten aufgeführt, wie Sie die Adresse abrufen können.
  + Wenn Ihr lokaler Computer (von dem aus Sie eine Verbindung zu Ihrer EC2-Instance herstellen) über eine statische öffentliche IP-Adresse verfügt, können Sie einen Dienst verwenden, um diese Adresse abzurufen. Ein solcher Dienst ist [http://checkip.amazonaws.com/](http://checkip.amazonaws.com/). Weitere Informationen zur Autorisierung von eingehendem Datenverkehr finden [Sie unter Hinzufügen von Regeln zu einer Sicherheitsgruppe](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html#adding-security-group-rule) und [Sicherheitsgruppenregeln für verschiedene Anwendungsfälle](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules-reference.html) im [Amazon EC2 EC2-Benutzerhandbuch](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).
  + Eine andere Möglichkeit, die IP-Adresse Ihres lokalen Computers zu erhalten, ist die Verwendung der [Amazon EC2 EC2-Konsole](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups).

    Wählen Sie eine Ihrer Sicherheitsgruppen aus, klicken Sie auf die Registerkarte **Regeln für eingehenden Datenverkehr und dann auf Regeln für eingehenden** **Datenverkehr bearbeiten**. Öffnen Sie in einer Regel für eingehenden Datenverkehr das Dropdownmenü in der Spalte **Quelle** und wählen Sie **Meine IP** aus, um die IP-Adresse Ihres lokalen Computers im CIDR-Format anzuzeigen. Achten Sie darauf, den **Vorgang abzubrechen**.
+ Sie können die Ergebnisse dieses Beispiels überprüfen, indem Sie die Liste der Sicherheitsgruppen in der [Amazon EC2 EC2-Konsole](https://console.aws.amazon.com/ec2/v2/home#SecurityGroups) überprüfen.