2012-03-15 129 views
7

我能夠在文法上將單獨的規則添加到Windows防火牆(Server 2008 R2),但是我試圖避免每個IP地址有多個規則,並且只想更新現有規則RemoteAddresses 。以下是我用來添加規則的代碼,我正在盡力研究如何更新現有規則遠程地址,但沒有運氣。使用API​​更新現有的防火牆規則

任何幫助表示讚賞!

string ip = "x.x.x.x"; 

INetFwRule2 firewallRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); 

firewallRule.Name = "Block Bad IP Addresses"; 
firewallRule.Description = "Block Nasty Incoming Connections from IP Address."; 
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; 
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; 
firewallRule.Enabled = true; 
firewallRule.InterfaceTypes = "All"; 
firewallRule.RemoteAddresses = ip; 

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

請避免在C#或類似的東西,這是標籤的用途。 – 2012-03-15 01:41:43

回答

10

下面的代碼爲我工作:

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

var rule = firewallPolicy.Rules.Item("Block Bad IP Addresses"); // Name of your rule here 
rule.Name = "Block Block Block"; // Update the rule here. Nothing else needed to persist the changes 
+0

是否有任何方法來解鎖封鎖的IP,我的意思是說更新規則 – Arshad 2013-02-28 07:55:27

+0

您可以更改rule.RemoteAddresses(以逗號分隔) – 2013-08-19 08:30:06

+2

對於那些測試此代碼的提示:所做的更改如上所述持久,但可能不會出現在具有高級安全_應用程序的Windows防火牆,直到刷新顯示爲止。 – HABO 2014-05-20 21:43:30

4

除了amdmax的答案(抱歉,我不能添加評論),我發現,有沒有簡單的方法調用檢查是否一個規則存在,所以我想出了這個以確保一個規則是否存在或不存在:

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

    INetFwRule firewallRule = firewallPolicy.Rules.OfType<INetFwRule>().Where(x => x.Name == RULE_NAME).FirstOrDefault(); 

    if (firewallRule == null) 
    { 
    firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")); 
    firewallRule.Name = RULE_NAME; 
    firewallPolicy.Rules.Add(firewallRule); 
    }