如何使用PowerShell列出订阅中所有VM的所有入站规则?

问题描述 投票:0回答:1

我想列出使用PowerShell为VM打开的入站规则中的所有端口。

我发现Network Security组可以连接到NIC或Vnet。

任何人都可以共享一个脚本,我可以使用PowerShell查看VM的入站规则吗?

azure powershell azure-virtual-machine
1个回答
0
投票

尝试如下命令,$rule是你想要的,你可以通过$rule.Name检查。

$rgs = (Get-AzResourceGroup).ResourceGroupName
foreach($rg in $rgs){

  $vms = (Get-AzVM -ResourceGroupName $rg).Name

  foreach($vm in $vms){

    $nicname = ((Get-AzVM -ResourceGroupName $rg -Name $vm).NetworkProfile.NetworkInterfaces.Id -split"/")[8]

    $nic = Get-AzResource -ResourceGroupName $rg -ResourceType Microsoft.Network/networkInterfaces -ResourceName "$nicname" -ApiVersion 2018-07-01
    $nsgnic = ($nic.properties.networkSecurityGroup.id -split"/")[8]

    $rulenic = (Get-AzNetworkSecurityGroup -ResourceGroupName $rg -Name $nsgnic).SecurityRules
    $ruledefault = (Get-AzNetworkSecurityGroup -ResourceGroupName $rg -Name $nsgnic).DefaultSecurityRules | Where-Object {$_.Direction -eq 'Inbound'}
    $rulenic1 = $rulenic + $ruledefault 


    $vnetname = (Get-AzNetworkInterface -ResourceGroupName $rg -Name $nicname).IpConfigurations.Subnet.Id.Split("/")[8]
    $subname = (Get-AzNetworkInterface -ResourceGroupName $rg -Name $nicname).IpConfigurations.Subnet.Id.Split("/")[10]



    $subnet = Get-AzResource -ResourceGroupName $rg -ResourceType Microsoft.Network/virtualNetworks/subnets -ResourceName "$vnetname/$subname" -ApiVersion 2018-07-01
    $nsgsub = ($subnet.properties.networkSecurityGroup.id -split"/")[8]
    $rulesub = (Get-AzNetworkSecurityGroup -ResourceGroupName $rg -Name $nsgsub).SecurityRules
    $ruledefault1 = (Get-AzNetworkSecurityGroup -ResourceGroupName $rg -Name $nsgsub).DefaultSecurityRules | Where-Object {$_.Direction -eq 'Inbound'}
    $rulsub1 = $rulesub + $ruledefault1


    $rule = $rulenic1 + $rulsub1
    Write-Output $rule.Name

  }


}

我在一个资源组中测试它,对于整个订阅,只需添加一个如上所述的循环。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.