远程更改防火墙(windows)规则(C#)

 自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的身份调用

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值