Programmatically add an application to all profile Windows Firewall (Vista+)

泪湿孤枕 提交于 2019-12-06 01:55:48

问题


I have searched around and there are similar questions on SO, however, no one talks about how to add exception to "All Profile" (windows 7, AKA "Any Profile" on Vista/Windows Server 2008). Examples on internet talk about add to current profile only.

The reason for this is I have a problem with one of my virtual machine: windows 2008 x86, current firewall profile is Domain, and my application is added to Exception list of Domain. (Firewall setting is as default: block any inbound calls that are not in exception list.) However, inbound calls are still blocked unless : 1. turn off firewall on that this virtual machine. 2. manually change rule profile of my application to "any"

It is very confusing as I thought only active profile should be "active" and should be functional, no matter other profiles are blocking my application inbound calls.

I am using XPSP2 INetFwMgr interface to add exceptions which is lacking of "any" profile support.

I am using c# but any language with example will be appreciated.


回答1:


You may try something like this:

using System;
using NetFwTypeLib;

namespace FirewallManager

{
  class Program
  {
    static void Main(string[] args)
    {
        INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
        firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
        firewallRule.Description = "Allow notepad";
        firewallRule.ApplicationName = @"C:\Windows\notepad.exe";
        firewallRule.Enabled = true;
        firewallRule.InterfaceTypes = "All";
        firewallRule.Name = "Notepad";

        INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
            Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
        firewallPolicy.Rules.Add(firewallRule);

    }
  }
}

For sake of completeness, add reference to c:\Windows\System32\FirewallAPI.dll



来源:https://stackoverflow.com/questions/5641839/programmatically-add-an-application-to-all-profile-windows-firewall-vista

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!