我想列出使用PowerShell为VM打开的入站规则中的所有端口。
我发现Network Security组可以连接到NIC或Vnet。
任何人都可以共享一个脚本,我可以使用PowerShell查看VM的入站规则吗?
尝试如下命令,$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
}
}
我在一个资源组中测试它,对于整个订阅,只需添加一个如上所述的循环。