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