Использование Powershell для управления IP-ограничениями в IIsWebVirtualDir - PullRequest
2 голосов
/ 01 июля 2011

Возникли проблемы с использованием Powershell для манипулирования ограничениями IP-адресов в IIsWebVirtualDir (виртуальные каталоги).

Однако у меня есть код для этого в VBS, так что, надеюсь, это будет простой вопрос, с которым можно получить помощь :)

Код в VBS:

 Sub Add2IPRList(WebsiteADSI, strIP2Add, strIP2AddSubnet)
    Set WebRootObj = GetObject(WebsiteADSI) '"IIS://localhost/W3SVC/2/ROOT/TestVDIR"
    set IPSecObj = WebRootObj.IPSecurity
    If(IPSecObj.GrantByDefault)then
        IPList = IPSecObj.IPDeny
    Else
        IPList = IPSecObj.IPGrant
    End If

    ReDim Preserve IPList (Ubound(IPList)+1)     'resize local copy of IPList array to CurrentSize+1
    IPList(Ubound(IPList))=strIP2Add&","&strIP2AddSubnet     'add the entry to the end of the array


    If(IPSecObj.GrantByDefault)then
        IPSecObj.IPDeny = IPList
    Else
        IPSecObj.IPGrant = IPList
    End If

    WebRootObj.IPSecurity = IPSecObj
    WebRootObj.SetInfo        'apply the setttings on the server.
    set IPSecObj = Nothing
    set WebRootObj = Nothing    
End Sub

Попытка 1 в Powershell: объект возвращается, но имеет странный тип.

PS C:\> $vdir=[adsi]"IIS://localhost/W3SVC/2/ROOT/TestVDIR";([adsi]$vdir).IPSecurity;
System.__ComObject

Попытка 2 в Powershell: Theобъект не возвращает

PS C:\> $VDir = Get-WmiObject -Namespace 'root\MicrosoftIISv2' -Class IIsWebVirtualDir |where ($_.name).contains("TestVDIR")};$VDir.IPSecurity;
PS C:\> 

Кто-нибудь знает, как 1) иметь дело с Системой .__ ComObject при использовании ADSI в Powershell или 2) иметь представление о том, как работать с объектом IPSecurity в IIS6 через поставщика WMI вPowershell?

Дополнительно:

Я нашел способ получить и изменить объект IIsIPSecuritySetting, связанный с W3SVC / 2 / ROOT / TestVDIR, используя следующий код.

param([string]$computer, [string]$W3SVCPath, [string]$strIP2Add, [string]$strIP2AddSubnet)
<# $W3SVCPath = "W3SVC/2/ROOT/TestVDir" #>;
$IPSecurity = Get-WmiObject -Authentication PacketPrivacy -class IIsIPSecuritySetting -computername $computer -namespace 'root\MicrosoftIISv2' | where {($_.name).equals("$W3SVCPath")};
if($IPSecurity.GrantByDefault){$GD="Deny"}else{$GD="Grant"}
if($IPSecurity.GrantByDefault){$IPList=$IPSecurity.IPDeny;}else{$IPList=$IPSecurity.IPGrant;};
"IPSecurity.GrantByDefault=$GD($IPList)";
$IPList=$IPList+"$strIP2Add, $strIP2AddSubnet";
if($IPSecurity.GrantByDefault){$IPSecurity.IPDeny=$IPList;}else{$IPSecurity.IPGrant=$IPList;};
if($IPSecurity.GrantByDefault){$IPList=$IPSecurity.IPDeny;}else{$IPList=$IPSecurity.IPGrant;};
"($IPList)";

Я не могу найти способ установить объект обратно в метабазу, чтобы он применил изменения.В VBS на объект IPSecurity всегда ссылались непосредственно в WebRootObj, и поэтому использовалась функция .setInfo ().Однако, поскольку мы собираемся непосредственно для класса объекта WMI и ссылки устанавливаются внутри самого объекта, я не могу найти функцию, которая установит его в классе IIsIPSecuritySettings.

Поскольку я не могу найтиссылка на свойство / объект IPSecurity в WebRootObj при использовании вышеупомянутой «Попытки 2 в Powershell», которая использует WMI, я не уверен, в каком направлении двигаться дальше.

Есть мысли?

1 Ответ

5 голосов
/ 26 января 2012

Это может быть сложно, но выполнимо, используя System.DirectoryServices.Я приведу два примера: один для установки значения GrantByDefault на true или false, другой для демонстрации того, как добавить IP-адреса в список IPDeny или IPGrant.

1,Установите GrantByDefault значение

$iisObject = new-object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/2/ROOT/TestVDIR")
$ipSec = $iisObject.Properties["IPSecurity"].Value

# We need to pass values as one element object arrays
[Object[]] $grantByDefault = @()
$grantByDefault += , $false            # <<< We're setting it to false

$ipSec.GetType().InvokeMember("GrantByDefault", $bindingFlags, $null, $ipSec, $grantByDefault);

$iisObject.Properties["IPSecurity"].Value = $ipSec
$iisObject.CommitChanges()

2.Добавьте IP-адрес в списки IPDeny или IPGrant

$iisObject = new-object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/2/ROOT/TestVDIR")
$ipSec = $iisObject.Properties["IPSecurity"].Value
$bindingFlags = [Reflection.BindingFlags] "Public, Instance, GetProperty"
$isGrantByDefault = $ipSec.GetType().InvokeMember("GrantByDefault", $bindingFlags, $null, $ipSec, $null);

# to set an iplist we need to get it first
if($isGrantByDefault)
{
    $ipList = $ipSec.GetType().InvokeMember("IPDeny", $bindingFlags, $null, $ipSec, $null);
}
else
{
    $ipList = $ipSec.GetType().InvokeMember("IPGrant", $bindingFlags, $null, $ipSec, $null);
}

# Add a single computer to the list:
$ipList = $ipList + "10.0.0.1, 255.255.255.255"

# This is important, we need to pass an object array of one element containing our ipList array
[Object[]] $ipArray = @()
$ipArray += , $ipList

# Now update
$bindingFlags = [Reflection.BindingFlags] "Public, Instance, SetProperty"
if($isGrantByDefault)
{
    $ipList = $ipSec.GetType().InvokeMember("IPDeny", $bindingFlags, $null, $ipSec, $ipArray);
}
else
{
    $ipList = $ipSec.GetType().InvokeMember("IPGrant", $bindingFlags, $null, $ipSec, $ipArray);
}

$iisObject.Properties["IPSecurity"].Value = $ipSec
$iisObject.CommitChanges()

Это было протестировано с PowerShell 2.0 в Windows 2003.

Надеюсь, еще не поздно спасти ваш день.

...