1

我有一个用于查找所有入站的脚本,允许 Azure NSG 中的规则是任何源。它正在完成他的工作,但只需要大量时间来迭代 Azure 中每个可用 NSG 中的每个规则。

问题是有什么方法可以优化它,所以它可以更快地工作吗?谢谢!

function nsg {

# List of default rules which are skipped

$array =
'Default rules'

# Get all RG with NSG

$RGS = (Get-AzureRmResource -ODataQuery "`$filter=resourcetype eq 'Microsoft.Network/networkSecurityGroups'").ResourceGroupName | Sort-Object -Unique

foreach ($RG in $RGS) { 

# List of all NSG names

$NSG_Names = (Get-AzureRmNetworkSecurityGroup -ResourceGroupName $RG).Name

# Get NSG rules

foreach ($NSG_Name in $NSG_Names){

$Rules = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig | Select-Object -ExpandProperty Name

# Check if rule is not default

foreach ($Rule in $Rules){

    if ($array.contains($Rule)){

    Write-Verbose "$Rule excluded because it is default!"

    }
else {

    Write-Verbose "$NSG_Name - $Rule"

    #$DestinationAddressPrefix = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty DestinationAddressPrefix
    $DestinationPortRange = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty DestinationPortRange
    $SourceAddrPref = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty SourceAddressPrefix
    $SourcePortRange = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty SourcePortRange
    $Access = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty Access
    $Direction = Get-AzureRmNetworkSecurityGroup -Name $NSG_Name -ResourceGroupName $RG | Get-AzureRmNetworkSecurityRuleConfig -Name $Rule | Select-Object -ExpandProperty Direction

# Chek rule for every criterion, access type, etc.

    if ($Direction -eq "Inbound" -and $SourceAddrPref -eq "*" -and $Access -eq "Allow"){ #-and $DestinationAddressPrefix -eq "*" -and $DestinationPortRange -eq "*") {

       $message = "Warning! RG: $RG; NSG: $NSG_Name has SOURCE ANY Rule: $Rule to Destionation Port: $DestinationPortRange"
       $message

}}}}}}
4

1 回答 1

1

我认为您不需要迭代所有这些数据。所有这些嵌套循环+排序是导致减速的原因。

在我看来,您只想输出所有带有方向Inbound和访问权限的 NSG Allow,源地址前缀为*. 如果是这种情况,您可以这样做:

$nsgs = Get-AzureRmNetworkSecurityGroup

foreach ($nsg in $nsgs.SecurityRules)
{
    if ($nsg.Direction -eq "Inbound" -and $nsg.Access -eq "Allow" -and $nsg.SourceAddressPrefix -eq "*")
    {
        $nsg
    }
}

在这里,我们只是迭代您从中制定的安全规则$nsgs.SecurityRules。默认的是在$nsgs.DefaultSecurityRules. 您可以通过管道Get-Member找到这些属性。

于 2020-04-13T09:44:06.237 回答