自windows的vista之后的版本中,可以直接使用dcom的方式调用另外一台机器上的firewall.dll更改相应的规则,当然需要grouppolicy的支持,也可以自己添加一天规则,应许你的这台计算机在另一台计算机上做相应操作,如下实现了一个更改firewall规则的方法:
/// <summary>
/// Uing Firewallapi.dll to Set the firewall rules.
/// When you want to change rules in firewall,just provide the name of rules that already exit rules'name in firewall
/// </summary>
/// <param name="destName">The name of destinate machine that will be set</param>
/// <param name="rulesName">The name of rule that will be set</param>
/// <param name="isRuleEnable">Set the rule enable or disable</param>
/// <param name="isActionAllow">Set the action of rule allowed or not allowed</param>
public void SetFwRule(string destName, string rulesName, bool isRuleEnable,bool isActionAllow)
{
if (destName == "" || rulesName == null)
{
throw new Exception("The destName or rulesName is empty");
}
System.Type type = Type.GetTypeFromProgID(progID, destName, true);
object policyObject = Activator.CreateInstance(type);
INetFwPolicy2 poclicy2 = policyObject as INetFwPolicy2;
INetFwRules rules = poclicy2.Rules;
if (rules == null)
{
throw new Exception("The rules is null");
}
//find the rule and change it
INetFwRule rule = rules.Item(rulesName);
if (rule == null)
{
throw new Exception("The rule is null,maybe the rule name failed");
}
//set the rule enable or not
if (isRuleEnable)
{
rule.Enabled = true;
}
else
{
rule.Enabled = false;
}
//set action of rule
if (isActionAllow)
{
rule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
}
else
{
rule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
}
}
PS:必须以Administrator的身份调用