使用 PowerShell 透過網路安全性群組篩選網路流量Filter network traffic with a network security group using PowerShell

注意

本文已更新為使用新的 Azure PowerShell Az 模組。This article has been updated to use the new Azure PowerShell Az module. AzureRM 模組在至少 2020 年 12 月之前都還會持續收到錯誤 (Bug) 修正,因此您仍然可以持續使用。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要深入了解新的 Az 模組和 AzureRM 的相容性,請參閱新的 Azure PowerShell Az 模組簡介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 如需 Az 模組安裝指示,請參閱安裝 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

您可以透過網路安全性群組篩選輸入虛擬網路子網路和從中輸出的網路流量。You can filter network traffic inbound to and outbound from a virtual network subnet with a network security group. 網路安全性群組包含可依 IP 位址、連接埠和通訊協定篩選網路流量的安全性規則。Network security groups contain security rules that filter network traffic by IP address, port, and protocol. 安全性規則會套用至子網路中部署的資源。Security rules are applied to resources deployed in a subnet. 在本文中,您將了解:In this article, you learn how to:

  • 建立網路安全性群組和安全性規則Create a network security group and security rules
  • 建立虛擬網路,並將網路安全性群組與子網路產生關聯Create a virtual network and associate a network security group to a subnet
  • 將虛擬機器 (VM) 部署至子網路中Deploy virtual machines (VM) into a subnet
  • 測試流量篩選Test traffic filters

如果您沒有 Azure 訂用帳戶,請在開始前建立 免費帳戶If you don't have an Azure subscription, create a free account before you begin.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. Cloud Shell 可讓您使用 bashPowerShell 以與 Azure 服務搭配使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文提到的程式碼,而不必在本機環境上安裝任何工具。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要啟動 Azure Cloud Shell:To launch Azure Cloud Shell:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 選取 [試用] 並不會自動將程式碼複製到 Cloud Shell 中。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的試試看範例
請前往 https://shell.azure.com 或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新視窗中啟動 Cloud ShellLaunch Cloud Shell in a new window
選取 Azure 入口網站右上角功能表列中的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

若要在 Azure Cloud Shell 中執行本文中的程式碼:To run the code in this article in Azure Cloud Shell:

  1. 啟動 Cloud Shell。Launch Cloud Shell.

  2. 選取程式碼區塊上的 [複製] 按鈕,複製程式碼。Select the Copy button on a code block to copy the code.

  3. 在 Windows 和 Linux 上按 Ctrl+Shift+V;或在 macOS 上按 Cmd+Shift+V,將程式碼貼到 Cloud Shell工作階段中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.

  4. 按下 Enter 鍵執行程式碼。Press Enter to run the code.

如果您選擇在本機安裝和使用 PowerShell,本文會要求使用 Azure PowerShell 模組 1.0.0 版或更新版本。If you choose to install and use PowerShell locally, this article requires the Azure PowerShell module version 1.0.0 or later. 執行 Get-Module -ListAvailable Az 來了解安裝的版本。Run Get-Module -ListAvailable Az to find the installed version. 如果您需要升級,請參閱安裝 Azure PowerShell 模組If you need to upgrade, see Install Azure PowerShell module. 如果您在本機執行 PowerShell,則也需要執行 Connect-AzAccount 以建立與 Azure 的連線。If you are running PowerShell locally, you also need to run Connect-AzAccount to create a connection with Azure.

建立網路安全性群組Create a network security group

網路安全性群組包含安全性規則。A network security group contains security rules. 安全性規則可指定來源和目的地。Security rules specify a source and destination. 來源和目的地可以是應用程式安全性群組。Sources and destinations can be application security groups.

建立應用程式安全性群組Create application security groups

第一次建立這篇文章中所建立的所有資源的資源群組新增 AzResourceGroupFirst create a resource group for all the resources created in this article with New-AzResourceGroup. 下列範例會在 eastus 位置建立資源群組:The following example creates a resource group in the eastus location:

New-AzResourceGroup -ResourceGroupName myResourceGroup -Location EastUS

建立與應用程式安全性群組新增 AzApplicationSecurityGroupCreate an application security group with New-AzApplicationSecurityGroup. 應用程式安全性群組可讓您將具有類似連接埠篩選需求的伺服器分組在一起。An application security group enables you to group servers with similar port filtering requirements. 下列範例會建立兩個應用程式安全性群組。The following example creates two application security groups.

$webAsg = New-AzApplicationSecurityGroup `
  -ResourceGroupName myResourceGroup `
  -Name myAsgWebServers `
  -Location eastus

$mgmtAsg = New-AzApplicationSecurityGroup `
  -ResourceGroupName myResourceGroup `
  -Name myAsgMgmtServers `
  -Location eastus

建立安全性規則Create security rules

建立安全性規則新增 AzNetworkSecurityRuleConfigCreate a security rule with New-AzNetworkSecurityRuleConfig. 下列範例會建立允許透過連接埠 80 和 443 從網際網路將流量輸入 myWebServers 應用程式安全性群組的規則:The following example creates a rule that allows traffic inbound from the internet to the myWebServers application security group over ports 80 and 443:

$webRule = New-AzNetworkSecurityRuleConfig `
  -Name "Allow-Web-All" `
  -Access Allow `
  -Protocol Tcp `
  -Direction Inbound `
  -Priority 100 `
  -SourceAddressPrefix Internet `
  -SourcePortRange * `
  -DestinationApplicationSecurityGroupId $webAsg.id `
  -DestinationPortRange 80,443

The following example creates a rule that allows traffic inbound from the internet to the *myMgmtServers* application security group over port 3389:

$mgmtRule = New-AzNetworkSecurityRuleConfig `
  -Name "Allow-RDP-All" `
  -Access Allow `
  -Protocol Tcp `
  -Direction Inbound `
  -Priority 110 `
  -SourceAddressPrefix Internet `
  -SourcePortRange * `
  -DestinationApplicationSecurityGroupId $mgmtAsg.id `
  -DestinationPortRange 3389

在本文中,會針對 myAsgMgmtServers VM 將 RDP (連接埠 3389) 公開至網際網路。In this article, RDP (port 3389) is exposed to the internet for the myAsgMgmtServers VM. 在生產環境中則不應將連接埠 3389 公開至網際網路,而是建議您使用 VPN私人網路連線連接到您想要管理的 Azure 資源。For production environments, instead of exposing port 3389 to the internet, it's recommended that you connect to Azure resources that you want to manage using a VPN or private network connection.

建立網路安全性群組Create a network security group

使用 New-AzNetworkSecurityGroup 建立網路安全性群組。Create a network security group with New-AzNetworkSecurityGroup. 下列範例會建立名為 myNsg 的網路安全性群組:The following example creates a network security group named myNsg:

$nsg = New-AzNetworkSecurityGroup `
  -ResourceGroupName myResourceGroup `
  -Location eastus `
  -Name myNsg `
  -SecurityRules $webRule,$mgmtRule

建立虛擬網路Create a virtual network

使用 New-AzVirtualNetwork 建立虛擬網路。Create a virtual network with New-AzVirtualNetwork. 下列範例會建立名為 myVirtualNetwork 的虛擬網路:The following example creates a virtual named myVirtualNetwork:

$virtualNetwork = New-AzVirtualNetwork `
  -ResourceGroupName myResourceGroup `
  -Location EastUS `
  -Name myVirtualNetwork `
  -AddressPrefix 10.0.0.0/16

建立的子網路設定新增 AzVirtualNetworkSubnetConfig,然後將子網路組態寫入虛擬網路組 AzVirtualNetworkCreate a subnet configuration with New-AzVirtualNetworkSubnetConfig, and then write the subnet configuration to the virtual network with Set-AzVirtualNetwork. 下列範例會將名為 mySubnet 的子網路新增至虛擬網路,並將其與 myNsg 網路安全性群組產生關聯:The following example adds a subnet named mySubnet to the virtual network and associates the myNsg network security group to it:

Add-AzVirtualNetworkSubnetConfig `
  -Name mySubnet `
  -VirtualNetwork $virtualNetwork `
  -AddressPrefix "10.0.2.0/24" `
  -NetworkSecurityGroup $nsg
$virtualNetwork | Set-AzVirtualNetwork

建立虛擬機器Create virtual machines

建立 Vm 之前, 擷取的子網路的虛擬網路物件Get AzVirtualNetwork:Before creating the VMs, retrieve the virtual network object with the subnet with Get-AzVirtualNetwork:

$virtualNetwork = Get-AzVirtualNetwork `
 -Name myVirtualNetwork `
 -Resourcegroupname myResourceGroup

用於每個 VM 建立公用 IP 位址新增 AzPublicIpAddress:Create a public IP address for each VM with New-AzPublicIpAddress:

$publicIpWeb = New-AzPublicIpAddress `
  -AllocationMethod Dynamic `
  -ResourceGroupName myResourceGroup `
  -Location eastus `
  -Name myVmWeb

$publicIpMgmt = New-AzPublicIpAddress `
  -AllocationMethod Dynamic `
  -ResourceGroupName myResourceGroup `
  -Location eastus `
  -Name myVmMgmt

建立具有兩個網路介面新增 AzNetworkInterface,並將公用 IP 位址指派給網路介面。Create two network interfaces with New-AzNetworkInterface, and assign a public IP address to the network interface. 下列範例會建立網路介面、將其與 myVmWeb 公用 IP 位址產生關聯,並使其成為 myAsgWebServers 應用程式安全性群組的成員:The following example creates a network interface, associates the myVmWeb public IP address to it, and makes it a member of the myAsgWebServers application security group:

$webNic = New-AzNetworkInterface `
  -Location eastus `
  -Name myVmWeb `
  -ResourceGroupName myResourceGroup `
  -SubnetId $virtualNetwork.Subnets[0].Id `
  -ApplicationSecurityGroupId $webAsg.Id `
  -PublicIpAddressId $publicIpWeb.Id

下列範例會建立網路介面、將其與 myVmMgmt 公用 IP 位址產生關聯,並使其成為 myAsgMgmtServers 應用程式安全性群組的成員:The following example creates a network interface, associates the myVmMgmt public IP address to it, and makes it a member of the myAsgMgmtServers application security group:

$mgmtNic = New-AzNetworkInterface `
  -Location eastus `
  -Name myVmMgmt `
  -ResourceGroupName myResourceGroup `
  -SubnetId $virtualNetwork.Subnets[0].Id `
  -ApplicationSecurityGroupId $mgmtAsg.Id `
  -PublicIpAddressId $publicIpMgmt.Id

在虛擬網路中建立兩個 VM,以便在後續步驟中驗證流量篩選。Create two VMs in the virtual network so you can validate traffic filtering in a later step.

建立 VM 組態新增 AzVMConfig,然後建立 VM New-azvmCreate a VM configuration with New-AzVMConfig, then create the VM with New-AzVM. 下列範例會建立將作為 Web 伺服器的 VM。The following example creates a VM that will serve as a web server. -AsJob 選項會在背景建立虛擬機器,以便您繼續進行下一個步驟:The -AsJob option creates the VM in the background, so you can continue to the next step:

# Create user object
$cred = Get-Credential -Message "Enter a username and password for the virtual machine."

$webVmConfig = New-AzVMConfig `
  -VMName myVmWeb `
  -VMSize Standard_DS1_V2 | `
Set-AzVMOperatingSystem -Windows `
  -ComputerName myVmWeb `
  -Credential $cred | `
Set-AzVMSourceImage `
  -PublisherName MicrosoftWindowsServer `
  -Offer WindowsServer `
  -Skus 2016-Datacenter `
  -Version latest | `
Add-AzVMNetworkInterface `
  -Id $webNic.Id
New-AzVM `
  -ResourceGroupName myResourceGroup `
  -Location eastus `
  -VM $webVmConfig `
  -AsJob

建立作為管理伺服器的 VM:Create a VM to serve as a management server:

# Create user object
$cred = Get-Credential -Message "Enter a username and password for the virtual machine."

# Create the web server virtual machine configuration and virtual machine.
$mgmtVmConfig = New-AzVMConfig `
  -VMName myVmMgmt `
  -VMSize Standard_DS1_V2 | `
Set-AzVMOperatingSystem -Windows `
  -ComputerName myVmMgmt `
  -Credential $cred | `
Set-AzVMSourceImage `
  -PublisherName MicrosoftWindowsServer `
  -Offer WindowsServer `
  -Skus 2016-Datacenter `
  -Version latest | `
Add-AzVMNetworkInterface `
  -Id $mgmtNic.Id
New-AzVM `
  -ResourceGroupName myResourceGroup `
  -Location eastus `
  -VM $mgmtVmConfig

建立虛擬機器需要幾分鐘的時間。The virtual machine takes a few minutes to create. 在 VM 建立完成前,請勿繼續進行下一個步驟。Don't continue with the next step until Azure finishes creating the VM.

測試流量篩選Test traffic filters

請使用 Get-AzPublicIpAddress 來傳回 VM 的公用 IP 位址。Use Get-AzPublicIpAddress to return the public IP address of a VM. 以下範例會傳回 myVmMgmt VM 的公用 IP 位址:The following example returns the public IP address of the myVmMgmt VM:

Get-AzPublicIpAddress `
  -Name myVmMgmt `
  -ResourceGroupName myResourceGroup `
  | Select IpAddress

請從您的本機電腦使用下列命令,建立 myVmMgmt VM 的遠端桌面工作階段。Use the following command to create a remote desktop session with the myVmMgmt VM from your local computer. 以上一個命令傳回的 IP 位址取代 <publicIpAddress>Replace <publicIpAddress> with the IP address returned from the previous command.

mstsc /v:<publicIpAddress>

開啟所下載的 RDP 檔案。Open the downloaded RDP file. 如果出現提示,請選取 [連接]。If prompted, select Connect.

輸入您在建立虛擬機器時指定的使用者名稱和密碼 (您可能需要選取 [更多選擇],然後選取 [使用不同的帳戶] 以指定您在建立虛擬機器時輸入的認證),然後選取 [確定]。Enter the user name and password you specified when creating the VM (you may need to select More choices, then Use a different account, to specify the credentials you entered when you created the VM), then select OK. 您可能會在登入過程中收到憑證警告。You may receive a certificate warning during the sign-in process. 選取 [是] 以繼續進行連線。Select Yes to proceed with the connection.

由於允許連接埠 3389 從網際網路將流量輸入連結至 myVmMgmt VM 的網路介面所在的 myAsgMgmtServers 應用程式安全性群組,因此連線會成功。The connection succeeds, because port 3389 is allowed inbound from the internet to the myAsgMgmtServers application security group that the network interface attached to the myVmMgmt VM is in.

請從 myVmMgmt VM 使用 PowerShell 的下列命令,建立 myVmWeb VM 的遠端桌面工作階段:Use the following command to create a remote desktop connection to the myVmWeb VM, from the myVmMgmt VM, with the following command, from PowerShell:

mstsc /v:myvmWeb

由於每個網路安全性群組中的預設安全性規則允許透過所有連接埠在虛擬網路內的所有 IP 位址之間傳輸流量,因此連線會成功。The connection succeeds because a default security rule within each network security group allows traffic over all ports between all IP addresses within a virtual network. 您無法建立從網際網路到 myVmWeb VM 的遠端桌面連線,因為 myAsgWebServers 的安全性規則不允許從網際網路的連接埠 3389 輸入。You can't create a remote desktop connection to the myVmWeb VM from the internet because the security rule for the myAsgWebServers doesn't allow port 3389 inbound from the internet.

請從 PowerShell 使用下列命令在 myVmWeb VM 上安裝 Microsoft IIS:Use the following command to install Microsoft IIS on the myVmWeb VM from PowerShell:

Install-WindowsFeature -name Web-Server -IncludeManagementTools

完成 IIS 安裝之後,請將 myVmWeb VM 中斷連線,以留在 myVmMgmt VM 遠端桌面連線中。After the IIS installation is complete, disconnect from the myVmWeb VM, which leaves you in the myVmMgmt VM remote desktop connection. 若要檢視 IIS 歡迎使用 畫面,請開啟網際網路瀏覽器和瀏覽至 http://myVmWeb。To view the IIS welcome screen, open an internet browser and browse to http://myVmWeb.

從 myVmMgmt VM 中斷連線。Disconnect from the myVmMgmt VM.

在您的電腦上,從 PowerShell 輸入下列命令,以擷取 myVmWeb 伺服器的公用 IP 位址的:On your computer, enter the following command from PowerShell to retrieve the public IP address of the myVmWeb server:

Get-AzPublicIpAddress `
  -Name myVmWeb `
  -ResourceGroupName myResourceGroup `
  | Select IpAddress

若要確認您可以從 Azure 外部存取 myVmWeb Web 伺服器,請在電腦上開啟網際網路瀏覽器,並瀏覽至 http://<public-ip-address-from-previous-step>To confirm that you can access the myVmWeb web server from outside of Azure, open an internet browser on your computer and browse to http://<public-ip-address-from-previous-step>. 由於允許連接埠 80 從網際網路將流量輸入連結至 myVmWeb VM 的網路介面所在的 myAsgWebServers 應用程式安全性群組,因此連線會成功。The connection succeeds, because port 80 is allowed inbound from the internet to the myAsgWebServers application security group that the network interface attached to the myVmWeb VM is in.

清除資源Clean up resources

您可以使用 Remove-AzResourceGroup 來移除不再需要的資源群組,以及其所包含的所有資源:When no longer needed, you can use Remove-AzResourceGroup to remove the resource group and all of the resources it contains:

Remove-AzResourceGroup -Name myResourceGroup -Force

後續步驟Next steps

在本文中,您已建立網路安全性群組,並將其與虛擬網路子網路產生關聯。In this article, you created a network security group and associated it to a virtual network subnet. 若要深入了解網路安全性群組,請參閱網路安全性群組概觀管理網路安全性群組To learn more about network security groups, see Network security group overview and Manage a network security group.

Azure 依預設會路由傳送子網路之間的流量。Azure routes traffic between subnets by default. 您可以改採其他方式,例如,透過作為防火牆的 VM 路由傳送子網路之間的流量。You may instead, choose to route traffic between subnets through a VM, serving as a firewall, for example. 若要了解操作方式,請參閱建立路由表To learn how, see Create a route table.