使用 PowerShell 通过虚拟网络服务终结点限制对 PaaS 资源的网络访问Restrict network access to PaaS resources with virtual network service endpoints 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.

通过虚拟网络服务终结点,可将某些 Azure 服务资源限制为仅允许某个虚拟网络子网通过网络进行访问。Virtual network service endpoints enable you to limit network access to some Azure service resources to a virtual network subnet. 还可以删除对资源的 Internet 访问。You can also remove internet access to the resources. 服务终结点提供从虚拟网络到受支持 Azure 服务的直接连接,使你能够使用虚拟网络的专用地址空间访问 Azure 服务。Service endpoints provide direct connection from your virtual network to supported Azure services, allowing you to use your virtual network's private address space to access the Azure services. 通过服务终结点发往 Azure 资源的流量始终保留在 Azure 主干网络上。Traffic destined to Azure resources through service endpoints always stays on the Azure backbone network. 在本文中,学习如何:In this article, you learn how to:

  • 创建包含一个子网的虚拟网络Create a virtual network with one subnet
  • 添加子网并启用服务终结点Add a subnet and enable a service endpoint
  • 创建 Azure 资源并且仅允许从一个子网对其进行网络访问Create an Azure resource and allow network access to it from only a subnet
  • 将虚拟机 (VM) 部署到每个子网Deploy a virtual machine (VM) to each subnet
  • 确认从某个子网对资源的访问Confirm access to a resource from a subnet
  • 确认已拒绝从某个子网和 Internet 来访问资源Confirm access is denied to a resource from a subnet and the internet

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

如果选择在本地安装和使用 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. 如果需要进行升级,请参阅 Install Azure PowerShell module(安装 Azure PowerShell 模块)。If you need to upgrade, see Install Azure PowerShell module. 如果在本地运行 PowerShell,则还需运行 Connect-AzAccount -Environment AzureChinaCloud 来创建与 Azure 的连接。If you are running PowerShell locally, you also need to run Connect-AzAccount -Environment AzureChinaCloud to create a connection with Azure.

创建虚拟网络Create a virtual network

创建虚拟网络之前,必须为虚拟网络创建资源组以及本文中创建的所有其他资源。Before creating a virtual network, you have to create a resource group for the virtual network, and all other resources created in this article. 使用 New-AzResourceGroup 创建资源组。Create a resource group with New-AzResourceGroup. 以下示例创建名为 myResourceGroup 的资源组:The following example creates a resource group named myResourceGroup:

Connect-AzAccount -Environment AzureChinaCloud
New-AzResourceGroup -ResourceGroupName myResourceGroup -Location ChinaEast

使用 New-AzVirtualNetwork 创建虚拟网络。Create a virtual network with New-AzVirtualNetwork. 以下示例使用地址前缀 10.0.0.0/16 创建一个名为 myVirtualNetwork 的虚拟网络。The following example creates a virtual network named myVirtualNetwork with the address prefix 10.0.0.0/16.

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

使用 New-AzVirtualNetworkSubnetConfig 创建子网配置。Create a subnet configuration with New-AzVirtualNetworkSubnetConfig. 以下示例为名为 Public 的子网创建子网配置:The following example creates a subnet configuration for a subnet named Public:

$subnetConfigPublic = Add-AzVirtualNetworkSubnetConfig `
  -Name Public `
  -AddressPrefix 10.0.0.0/24 `
  -VirtualNetwork $virtualNetwork

通过使用 Set-AzVirtualNetwork 将子网配置写入虚拟网络,在虚拟网络中创建子网:Create the subnet in the virtual network by writing the subnet configuration to the virtual network with Set-AzVirtualNetwork:

$virtualNetwork | Set-AzVirtualNetwork

启用服务终结点Enable a service endpoint

只能为支持服务终结点的服务启用服务终结点。You can enable service endpoints only for services that support service endpoints. 使用 Get-AzVirtualNetworkAvailableEndpointService 查看某个 Azure 位置中可用的启用了服务终结点的服务。View service endpoint-enabled services available in an Azure location with Get-AzVirtualNetworkAvailableEndpointService. 以下示例返回 chinaeast 区域中可用的启用了服务终结点的服务列表。The following example returns a list of service-endpoint-enabled services available in the chinaeast region. 随着更多的 Azure 服务启用服务终结点,返回的服务列表将随时间增大。The list of services returned will grow over time as more Azure services become service endpoint enabled.

Get-AzVirtualNetworkAvailableEndpointService -Location chinaeast | Select Name

在虚拟网络中创建另一个子网。Create an additional subnet in the virtual network. 在此示例中,将创建一个包含用于 Microsoft.Storage 的服务终结点且名为 Private 的子网:In this example, a subnet named Private is created with a service endpoint for Microsoft.Storage:

$subnetConfigPrivate = Add-AzVirtualNetworkSubnetConfig `
  -Name Private `
  -AddressPrefix 10.0.1.0/24 `
  -VirtualNetwork $virtualNetwork `
  -ServiceEndpoint Microsoft.Storage

$virtualNetwork | Set-AzVirtualNetwork

限制子网的网络访问Restrict network access for a subnet

使用 New-AzNetworkSecurityRuleConfig 创建网络安全组安全规则。Create network security group security rules with New-AzNetworkSecurityRuleConfig. 以下规则允许对分配给 Azure 存储服务的公共 IP 地址进行出站访问:The following rule allows outbound access to the public IP addresses assigned to the Azure Storage service:

$rule1 = New-AzNetworkSecurityRuleConfig `
  -Name Allow-Storage-All `
  -Access Allow `
  -DestinationAddressPrefix Storage `
  -DestinationPortRange * `
  -Direction Outbound `
  -Priority 100 `
  -Protocol * `
  -SourceAddressPrefix VirtualNetwork `
  -SourcePortRange *

以下规则拒绝对所有公共 IP 地址的访问。The following rule denies access to all public IP addresses. 上一个规则将替代此规则,因为它的优先级更高,上一个规则允许对 Azure 存储的公共 IP 地址进行访问。The previous rule overrides this rule, due to its higher priority, which allows access to the public IP addresses of Azure Storage.

$rule2 = New-AzNetworkSecurityRuleConfig `
  -Name Deny-Internet-All `
  -Access Deny `
  -DestinationAddressPrefix Internet `
  -DestinationPortRange * `
  -Direction Outbound `
  -Priority 110 `
  -Protocol * `
  -SourceAddressPrefix VirtualNetwork `
  -SourcePortRange *

以下规则允许从任何位置到该子网的远程桌面协议 (RDP) 入站流量。The following rule allows Remote Desktop Protocol (RDP) traffic inbound to the subnet from anywhere. 将允许到该子网的远程桌面连接,以便你可以在后面的步骤中确认对资源的网络访问。Remote desktop connections are allowed to the subnet, so that you can confirm network access to a resource in a later step.

$rule3 = New-AzNetworkSecurityRuleConfig `
  -Name Allow-RDP-All `
  -Access Allow `
  -DestinationAddressPrefix VirtualNetwork `
  -DestinationPortRange 3389 `
  -Direction Inbound `
  -Priority 120 `
  -Protocol * `
  -SourceAddressPrefix * `
  -SourcePortRange *

使用 New-AzNetworkSecurityGroup 创建网络安全组。Create a network security group with New-AzNetworkSecurityGroup. 以下示例创建名为 myNsgPrivate 的网络安全组。The following example creates a network security group named myNsgPrivate.

$nsg = New-AzNetworkSecurityGroup `
  -ResourceGroupName myResourceGroup `
  -Location ChinaEast `
  -Name myNsgPrivate `
  -SecurityRules $rule1,$rule2,$rule3

使用 Set-AzVirtualNetworkSubnetConfig 将该网络安全组添加到 Private 子网,然后将子网配置写入到虚拟网络。Associate the network security group to the Private subnet with Set-AzVirtualNetworkSubnetConfig and then write the subnet configuration to the virtual network. 以下示例将 myNsgPrivate 网络安全组关联到 Private 子网:The following example associates the myNsgPrivate network security group to the Private subnet:

Set-AzVirtualNetworkSubnetConfig `
  -VirtualNetwork $VirtualNetwork `
  -Name Private `
  -AddressPrefix 10.0.1.0/24 `
  -ServiceEndpoint Microsoft.Storage `
  -NetworkSecurityGroup $nsg

$virtualNetwork | Set-AzVirtualNetwork

限制对资源的网络访问Restrict network access to a resource

对于通过为服务终结点启用的 Azure 服务创建的资源,限制对其的网络访问时所需的步骤因服务而异。The steps necessary to restrict network access to resources created through Azure services enabled for service endpoints varies across services. 请参阅各个服务的文档来了解适用于每个服务的具体步骤。See the documentation for individual services for specific steps for each service. 作为示例,本文的剩余部分包括了针对 Azure 存储帐户限制网络访问的步骤。The remainder of this article includes steps to restrict network access for an Azure Storage account, as an example.

创建存储帐户Create a storage account

使用 New-AzStorageAccount 创建 Azure 存储帐户。Create an Azure storage account with New-AzStorageAccount. <replace-with-your-unique-storage-account-name> 替换为在所有 Azure 位置中唯一的、长度为 3-24 个字符且仅使用数字和小写字母的名称。Replace <replace-with-your-unique-storage-account-name> with a name that is unique across all Azure locations, between 3-24 characters in length, using only numbers and lower-case letters.

$storageAcctName = '<replace-with-your-unique-storage-account-name>'

New-AzStorageAccount `
  -Location ChinaEast `
  -Name $storageAcctName `
  -ResourceGroupName myResourceGroup `
  -SkuName Standard_LRS `
  -Kind StorageV2

创建存储帐户后,使用 Get-AzStorageAccountKey 将存储帐户的密钥检索到一个变量中:After the storage account is created, retrieve the key for the storage account into a variable with Get-AzStorageAccountKey:

$storageAcctKey = (Get-AzStorageAccountKey `
  -ResourceGroupName myResourceGroup `
  -AccountName $storageAcctName).Value[0]

在后面的步骤中将使用此密钥来创建文件共享。The key is used to create a file share in a later step. 输入 $storageAcctKey 并记下值,因为你在后面的步骤中将文件共享映射到 VM 中的驱动器时还需要手动输入该值。Enter $storageAcctKey and note the value, as you'll also need to manually enter it in a later step when you map the file share to a drive in a VM.

在存储帐户中创建文件共享Create a file share in the storage account

使用 New-AzStorageContext 为存储帐户和密钥创建上下文。Create a context for your storage account and key with New-AzStorageContext. 该上下文封装了存储帐户名称和帐户密钥:The context encapsulates the storage account name and account key:

$storageContext = New-AzStorageContext $storageAcctName $storageAcctKey

使用 New-AzStorageShare 创建一个文件共享:Create a file share with New-AzStorageShare:

$share = New-AzStorageShare my-file-share -Context $storageContext$share = New-AzStorageShare my-file-share -Context $storageContext

拒绝对存储帐户的所有网络访问Deny all network access to a storage account

默认情况下,存储帐户接受来自任何网络中的客户端的网络连接。By default, storage accounts accept network connections from clients in any network. 若要仅允许所选的网络进行访问,请使用 Update-AzStorageAccountNetworkRuleSet 将默认操作更改为 DenyTo limit access to selected networks, change the default action to Deny with Update-AzStorageAccountNetworkRuleSet. 在拒绝网络访问后,将无法从任何网络访问存储帐户。Once network access is denied, the storage account is not accessible from any network.

Update-AzStorageAccountNetworkRuleSet  `
  -ResourceGroupName "myresourcegroup" `
  -Name $storageAcctName `
  -DefaultAction Deny

启用从子网的网络访问Enable network access from a subnet

使用 Get-AzVirtualNetwork 检索所创建的虚拟网络,然后使用 Get-AzVirtualNetworkSubnetConfig 将专用子网对象检索到一个变量中:Retrieve the created virtual network with Get-AzVirtualNetwork and then retrieve the private subnet object into a variable with Get-AzVirtualNetworkSubnetConfig:

$privateSubnet = Get-AzVirtualNetwork `
  -ResourceGroupName "myResourceGroup" `
  -Name "myVirtualNetwork" `
  | Get-AzVirtualNetworkSubnetConfig `
  -Name "Private"

使用 Add-AzStorageAccountNetworkRule 允许从 Private 子网对存储帐户进行网络访问。Allow network access to the storage account from the Private subnet with Add-AzStorageAccountNetworkRule.

Add-AzStorageAccountNetworkRule `
  -ResourceGroupName "myresourcegroup" `
  -Name $storageAcctName `
  -VirtualNetworkResourceId $privateSubnet.Id

创建虚拟机Create virtual machines

若要测试对存储帐户的网络访问,请向每个子网部署 VM。To test network access to a storage account, deploy a VM to each subnet.

创建第一个虚拟机Create the first virtual machine

使用 New-AzVM 在 Public 子网中创建虚拟机。Create a virtual machine in the Public subnet with New-AzVM. 运行以下命令时,会提示输入凭据。When running the command that follows, you are prompted for credentials. 输入的值将配置为用于 VM 的用户名和密码。The values that you enter are configured as the user name and password for the VM. -AsJob 选项会在后台创建 VM,因此可继续执行下一步。The -AsJob option creates the VM in the background, so that you can continue to the next step.

New-AzVm `
    -ResourceGroupName "myResourceGroup" `
    -Location "China East" `
    -VirtualNetworkName "myVirtualNetwork" `
    -SubnetName "Public" `
    -Name "myVmPublic" `
    -AsJob

将返回类似于以下示例输出的输出:Output similar to the following example output is returned:

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
1      Long Running... AzureLongRun... Running       True            localhost            New-AzVM     

创建第二个虚拟机Create the second virtual machine

Private 子网中创建一台虚拟机:Create a virtual machine in the Private subnet:

New-AzVm `
    -ResourceGroupName "myResourceGroup" `
    -Location "China East" `
    -VirtualNetworkName "myVirtualNetwork" `
    -SubnetName "Private" `
    -Name "myVmPrivate"

Azure 需要花费几分钟时间来创建 VM。It takes a few minutes for Azure to create the VM. 在 Azure 完成创建 VM 并将输出返回到 PowerShell 之前,请不要继续执行下一步骤。Do not continue to the next step until Azure finishes creating the VM and returns output to PowerShell.

确认对存储帐户的访问Confirm access to storage account

使用 Get-AzPublicIpAddress 返回 VM 的公共 IP 地址。Use Get-AzPublicIpAddress to return the public IP address of a VM. 以下示例返回 myVmPrivate VM 的公共 IP 地址:The following example returns the public IP address of the myVmPrivate VM:

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

在以下命令中将 <publicIpAddress> 替换为前一个命令返回的公共 IP 地址,然后输入以下命令:Replace <publicIpAddress> in the following command, with the public IP address returned from the previous command, and then enter the following command:

mstsc /v:<publicIpAddress>

此时会创建远程桌面协议 (.rdp) 文件,并下载到计算机。A Remote Desktop Protocol (.rdp) file is created and downloaded to your computer. 打开下载的 rdp 文件。Open the downloaded rdp file. 出现提示时,选择“连接”。If prompted, select Connect. 输入在创建 VM 时指定的用户名和密码。Enter the user name and password you specified when creating the VM. 可能需要选择“更多选择”,然后选择“使用其他帐户”,以指定在创建 VM 时输入的凭据。You may need to select More choices, then Use a different account, to specify the credentials you entered when you created the VM. 选择“确定” 。Select OK. 你可能会在登录过程中收到证书警告。You may receive a certificate warning during the sign-in process. 如果收到警告,请选择“是”或“继续”以继续连接。 If you receive the warning, select Yes or Continue, to proceed with the connection.

myVmPrivate VM 上,使用 PowerShell 将 Azure 文件共享映射到驱动器 Z。On the myVmPrivate VM, map the Azure file share to drive Z using PowerShell. 在运行下面的命令之前,将 <storage-account-key><storage-account-name> 替换为在创建存储帐户中提供或检索的值。Before running the commands that follow, replace <storage-account-key> and <storage-account-name> with values from you supplied or retrieved in Create a storage account.

$acctKey = ConvertTo-SecureString -String "<storage-account-key>" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList "Azure\<storage-account-name>", $acctKey
New-PSDrive -Name Z -PSProvider FileSystem -Root "\\<storage-account-name>.file.core.chinacloudapi.cn\my-file-share" -Credential $credential

PowerShell 将返回类似于以下示例的输出:PowerShell returns output similar to the following example output:

Name           Used (GB)     Free (GB) Provider      Root
----           ---------     --------- --------      ----
Z                                      FileSystem    \\vnt.file.core.chinacloudapi.cn\my-f...

Azure 文件共享已成功映射到驱动器 Z。The Azure file share successfully mapped to the Z drive.

确认 VM 没有到任何其他公共 IP 地址的出站连接:Confirm that the VM has no outbound connectivity to any other public IP addresses:

ping bing.com

你不会收到回复,因为除了分配给 Azure 存储服务的地址之外,关联到 Private 子网的网络安全组不允许对其他公共 IP 地址的出站访问。You receive no replies, because the network security group associated to the Private subnet does not allow outbound access to public IP addresses other than the addresses assigned to the Azure Storage service.

关闭与 myVmPrivate VM 建立的远程桌面会话。Close the remote desktop session to the myVmPrivate VM.

确认已拒绝对存储帐户的访问Confirm access is denied to storage account

获取 myVmPublic VM 的公共 IP 地址:Get the public IP address of the myVmPublic VM:

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

在以下命令中将 <publicIpAddress> 替换为前一个命令返回的公共 IP 地址,然后输入以下命令:Replace <publicIpAddress> in the following command, with the public IP address returned from the previous command, and then enter the following command:

mstsc /v:<publicIpAddress>

myVmPublic VM 上,尝试将 Azure 文件共享映射到驱动器 Z。在运行下面的命令之前,将 <storage-account-key><storage-account-name> 替换为在创建存储帐户中提供或检索的值。On the myVmPublic VM, attempt to map the Azure file share to drive Z. Before running the commands that follow, replace <storage-account-key> and <storage-account-name> with values from you supplied or retrieved in Create a storage account.

$acctKey = ConvertTo-SecureString -String "<storage-account-key>" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList "Azure\<storage-account-name>", $acctKey
New-PSDrive -Name Z -PSProvider FileSystem -Root "\\<storage-account-name>.file.core.chinacloudapi.cn\my-file-share" -Credential $credential

对该共享的访问被拒绝,并且将收到 New-PSDrive : Access is denied 错误。Access to the share is denied, and you receive a New-PSDrive : Access is denied error. 访问被拒绝,因为 myVmPublic VM 部署在“公共”子网中。Access is denied because the myVmPublic VM is deployed in the Public subnet. “公共”子网没有为 Azure 存储启用服务终结点,并且存储帐户仅允许来自“专用”子网的网络访问,不允许来自“公共”子网的网络访问。 The Public subnet does not have a service endpoint enabled for Azure Storage, and the storage account only allows network access from the Private subnet, not the Public subnet.

关闭与 myVmPublic VM 建立的远程桌面会话。Close the remote desktop session to the myVmPublic VM.

从计算机中,尝试使用以下命令查看存储帐户中的文件共享:From your computer, attempt to view the file shares in the storage account with the following command:

Get-AzStorageFile `
  -ShareName my-file-share `
  -Context $storageContext

访问被拒绝,并且你会收到 Get-AzStorageFile:远程服务器返回了错误:(403) 禁止访问。HTTP 状态代码:403 - HTTP 错误消息:此请求无权执行此操作 错误,因为你的计算机不在 MyVirtualNetwork 虚拟网络的 Private 子网中。Access is denied, and you receive a Get-AzStorageFile : The remote server returned an error: (403) Forbidden. HTTP Status Code: 403 - HTTP Error Message: This request is not authorized to perform this operation error, because your computer is not in the Private subnet of the MyVirtualNetwork virtual network.

清理资源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 enabled a service endpoint for a virtual network subnet. 我们已了解,可为通过多个 Azure 服务部署的资源启用服务终结点。You learned that service endpoints can be enabled for resources deployed with multiple Azure services. 我们创建了一个 Azure 存储帐户并将该存储帐户限制为仅可供某个虚拟网络子网中的资源进行网络访问。You created an Azure Storage account and limited network access to the storage account to only resources within a virtual network subnet. 若要详细了解服务终结点,请参阅服务终结点概述管理子网To learn more about service endpoints, see Service endpoints overview and Manage subnets.

如果帐户中有多个虚拟网络,可将两个虚拟网络连接到一起,使每个虚拟网络中的资源可以相互通信。If you have multiple virtual networks in your account, you may want to connect two virtual networks together so the resources within each virtual network can communicate with each other. 若要了解如何操作,请参阅连接虚拟网络To learn how, see Connect virtual networks.