windows系统防火墙应用程序出入站实现添加

使用com 组件:

 具体实现如下:

 

using System;
using NetFwTypeLib;

namespace FireWall
{
    public static class FireWallHelper
    {
        /// <summary>
        /// 将应用程序添加到防火墙例外
        /// </summary>
        /// <param name="ruleName">应用程序名称</param>
        /// <param name="applicationPath">应用程序可执行文件全路径</param>
        public static void NetFwAddApps(string ruleName, string applicationPath)
        {
            // 创建一个COM对象来访问Windows防火墙设置
            var type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            var firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(type);

            // 创建一个防火墙出站规则对象
            var firewallRuleOut = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            // 设置防火墙规则的属性
            firewallRuleOut.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            firewallRuleOut.Description = "Allow outbound traffic for My Application";
            firewallRuleOut.ApplicationName = applicationPath;
            firewallRuleOut.Name = ruleName;
            firewallRuleOut.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY;
            firewallRuleOut.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
            firewallRuleOut.Enabled = true;

            // 创建一个防火墙入站规则对象
            var firewallRuleIn = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

            // 设置防火墙规则的属性
            firewallRuleIn.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
            firewallRuleIn.Description = "Allow outbound traffic for My Application";
            firewallRuleIn.ApplicationName = applicationPath;
            firewallRuleIn.Name = ruleName;
            firewallRuleIn.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY;
            firewallRuleIn.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            firewallRuleIn.Enabled = true;

            var isExistsRuleOut = false;
            var isExistsRuleIn = false;
            // 遍历规则集合,检查规则名称是否存在
            foreach (INetFwRule rule in firewallPolicy.Rules)
            {
                if (rule.Name == ruleName)
                {
                    if (rule.Direction == firewallRuleOut.Direction)
                    {
                        isExistsRuleOut = true;
                    }

                    if (rule.Direction == firewallRuleIn.Direction)
                    {
                        isExistsRuleIn = true;
                    }
                }
            }

            if (!isExistsRuleOut)
            {
                // 将出站规则添加到防火墙策略中
                firewallPolicy.Rules.Add(firewallRuleOut);
            }

            if (!isExistsRuleIn)
            {
                // 将出站规则添加到防火墙策略中
                firewallPolicy.Rules.Add(firewallRuleIn);
            }
        }
    }
}

 

posted on 2024-09-25 09:45  TanZhiWei  阅读(22)  评论(0编辑  收藏  举报