以编程方式将IP添加到Server 2008防火墙规则

时间:2010-12-07 23:55:46

标签: windows-server-2008 firewall

有人知道如何以编程方式将IP地址添加到具有高级安全性的Server 2008 Windows防火墙规则吗?

即。我已经设置了阻止操作防火墙规则,该规则在Scope的“远程IP地址”部分下列出了一些IP地址。我希望能够以编程方式添加(或可能删除)此列表中的IP地址。是否有.NET对象可用于执行此操作?

4 个答案:

答案 0 :(得分:11)

可以在以下位置找到具有高级安全起始页的Windows防火墙:

http://msdn.microsoft.com/en-us/library/ff956124(v=VS.85).aspx

具体来说,您似乎需要在下面描述的INetFwRule接口:

http://msdn.microsoft.com/en-us/library/aa365344(v=VS.85).aspx

检查get_RemoteAddresses和put_RemoteAddresses

答案 1 :(得分:8)

您也可以尝试netsh环境 我用它一次来改变界面的MTU

答案 2 :(得分:6)

答案 3 :(得分:5)

我刚刚在vb.NET中完成了这项工作。 添加对“c:\ windows \ system32 \ firewallapi.dll”

的引用

创建一个名为防火墙的类 - 就像这样:

Imports NetFwTypeLib
Imports System.Net

Public Class Firewall
    Implements IDisposable
    Private _policy As INetFwPolicy2 = Nothing

    Private ReadOnly Property Policy As INetFwPolicy2
        Get
            If _policy Is Nothing Then
                _policy = DirectCast(Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")), INetFwPolicy2)
            End If
            Return _policy
        End Get
    End Property

    Public Sub Add(ipAddress As IPAddress, ruleName As String)
        Dim firewallRule As NetFwTypeLib.INetFwRule = Policy.Rules.Item(ruleName)
        Dim NewAddress As String = ipAddress.ToString & "/255.255.255.255"
        If Not firewallRule.RemoteAddresses.Contains(NewAddress) Then
            firewallRule.RemoteAddresses += "," & NewAddress
        End If
    End Sub

    Public Sub Remove(ipAddress As IPAddress, ruleName As String)
        Dim firewallRule As NetFwTypeLib.INetFwRule = Policy.Rules.Item(ruleName)
        Dim NewAddress As String = ipAddress.ToString & "/255.255.255.255"
        If firewallRule.RemoteAddresses.Contains(NewAddress) Then
            Dim ipList As String = firewallRule.RemoteAddresses
            ipList = ipList.Replace(NewAddress, "")
            ipList = ipList.Replace(",,", ",")
            firewallRule.RemoteAddresses = ipList
        End If
    End Sub

    Public Function Exists(ipAddress As IPAddress, ruleName As String) As Boolean
        Dim firewallRule As NetFwTypeLib.INetFwRule = Policy.Rules.Item(ruleName)
        Dim NewAddress As String = ipAddress.ToString & "/255.255.255.255"
        If firewallRule.RemoteAddresses.Contains(NewAddress) Then
            Return True
        Else
            Return False
        End If
    End Function

    Private disposedValue As Boolean
    Protected Overridable Sub Dispose(disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
            End If
            If Not _policy Is Nothing Then
                _policy = Nothing
            End If
        End If
        Me.disposedValue = True
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
End Class