通过win7 FirewallAPI将应用程序防火墙规则添加到专用和公用网络 [英] Adding an application firewall rule to both private and public networks via win7 FirewallAPI
问题描述
一些背景知识:基本上,我想向私有和公共网络都添加程序防火墙访问规则。
A little background: Basicaly I'd like to add a program firewall access rule to both private and public networks.
我以前使用过-
netsh防火墙添加允许的程序程序=路径。名称= AppName启用范围=所有配置文件=当前
I used to use this- "netsh firewall add allowedprogram program= "Path.." name=AppName ENABLE scope=ALL profile=CURRENT"
但是现在我想自动化该过程a很少使用COM对象。
找到了这段闪亮的代码- http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid= 42& mid = 404& ctl = Details& ItemID = 8
But now I'd like to automate the proccess a little using a COM object. Found this shiny piece of code - http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid=42&mid=404&ctl=Details&ItemID=8
在实现该类后,我一直在尝试使用-
FirewallHelper .Instance.GrantAuthorization(@ Path ..., AppName,NET_FW_SCOPE_.NET_FW_SCOPE_ALL,NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY);
And after implementing the class I've been trying to use- FirewallHelper.Instance.GrantAuthorization(@"Path... ","AppName ",NET_FW_SCOPE_.NET_FW_SCOPE_ALL,NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY);
我面临的问题是GrantAuthorization方法只会为公用或专用网络添加一条规则,而我以前的netsh命令会为每个网络添加2条规则-1。
The problem I'm facing is that the GrantAuthorization method will only add a rule for the public OR private network whereas my old netsh command would 2 rules for- 1 for each network.
这些命令实际上看起来非常相似,所以
The commands actually seems very similar so it is kinda buffling to me.
所以...如何添加两个网络规则?
So... how to add both network rules?
肖恩
推荐答案
我的回答来自大卫的回答,但更详细。并解决有关设置本地端口的问题。您需要先设置协议,然后再设置本地端口。下面是更多详细信息:
My answer is from David's answer but more detail. And fix problem about setting Localports. You need to setting Protocol before setting Localports. More detail is bellow:
首先,您需要导入参考FirewallAPI.dll。然后在 C:\Windows\System32\FirewallAPI.dll中
;
the first, you need to import reference FirewallAPI.dll. It's in "C:\Windows\System32\FirewallAPI.dll" then:
using NetFwTypeLib;
并将代码插入您的:
Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
var currentProfiles = fwPolicy2.CurrentProfileTypes;
// Let's create a new rule
INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
inboundRule.Enabled = true;
//Allow through firewall
inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
//Using protocol TCP
inboundRule.Protocol = 6; // TCP
//Port 81
inboundRule.LocalPorts = "81";
//Name of rule
inboundRule.Name = "MyRule";
// ...//
inboundRule.Profiles = currentProfiles;
// Now add the rule
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(inboundRule);
这篇关于通过win7 FirewallAPI将应用程序防火墙规则添加到专用和公用网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!