Updating existing firewall rule using API

前端 未结 3 1353
花落未央
花落未央 2021-02-06 02:02

I am able to pro grammatically add individual rules to the Windows Firewall (Server 2008 R2), however I am trying to avoid multiple rules per IP address, and would just like to

3条回答
  •  隐瞒了意图╮
    2021-02-06 02:11

    I have found this package it is available via nuget WindowsFirewallHelper

    PM> install-package WindowsFirewallHelper
    

    Example

    var rule = FirewallManager.Instance.Rules.Where(o => 
        o.Direction == FirewallDirection.Inbound &&
        o.Name.Equals("Allow Remote Desktop")
    ).FirstOrDefault();
    
    if (rule != null)
    {
        //Update an existing Rule
        rule.RemoteAddresses = new IAddress[]
        {
            SingleIP.Parse("192.168.184.1"),
            SingleIP.Parse("192.168.184.2")
        };
    
        return;
    }
    
    //Create a new rule
    rule = FirewallManager.Instance.CreateApplicationRule(
         FirewallManager.Instance.GetProfile().Type,
         @"Allow Remote Desktop",
         FirewallAction.Allow,
         null
    );
    
    rule.Direction = FirewallDirection.Inbound;
    rule.LocalPorts = new ushort[] { 3389 };
    rule.Action = FirewallAction.Allow;
    rule.Protocol = FirewallProtocol.TCP;
    rule.Scope = FirewallScope.All;
    rule.Profiles = FirewallProfiles.Public | FirewallProfiles.Private;
    rule.RemoteAddresses = new IAddress[] { SingleIP.Parse("192.168.184.1") };
    
    FirewallManager.Instance.Rules.Add(rule);
    

提交回复
热议问题