在 PowerShell 中使用 Azure 网络观察程序管理数据包捕获Manage packet captures with Azure Network Watcher using PowerShell

使用网络观察程序数据包捕获,可以创建捕获会话以跟踪进出虚拟机的流量。Network Watcher packet capture allows you to create capture sessions to track traffic to and from a virtual machine. 为捕获会话提供了筛选器以确保仅捕获所需的流量。Filters are provided for the capture session to ensure you capture only the traffic you want. 数据包捕获有助于以主动和被动方式诊断网络异常。Packet capture helps to diagnose network anomalies both reactively and proactively. 其他用途包括收集网络统计信息,获得网络入侵信息,调试客户端与服务器之间的通信,等等。Other uses include gathering network statistics, gaining information on network intrusions, to debug client-server communications and much more. 由于能够远程触发数据包捕获,此功能可减轻手动运行数据包捕获的负担,并可在所需计算机上运行,从而可节省宝贵的时间。By being able to remotely trigger packet captures, this capability eases the burden of running a packet capture manually and on the desired machine, which saves valuable time.

本文将引导完成当前可用于数据包捕获的不同管理任务。This article takes you through the different management tasks that are currently available for packet capture.

备注

本文已经过更新,以便使用 Azure Az PowerShell 模块。This article has been updated to use the Azure Az PowerShell module. 若要与 Azure 交互,建议使用的 PowerShell 模块是 Az PowerShell 模块。The Az PowerShell module is the recommended PowerShell module for interacting with Azure. 若要开始使用 Az PowerShell 模块,请参阅安装 Azure PowerShellTo get started with the Az PowerShell module, see Install Azure PowerShell. 若要了解如何迁移到 Az PowerShell 模块,请参阅 将 Azure PowerShell 从 AzureRM 迁移到 AzTo learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.

准备阶段Before you begin

本文假定你拥有以下资源:This article assumes you have the following resources:

  • 要创建数据包捕获的区域中的网络观察程序实例An instance of Network Watcher in the region you want to create a packet capture

  • 已启用数据包捕获扩展的虚拟机。A virtual machine with the packet capture extension enabled.

重要

数据包捕获需要虚拟机扩展 AzureNetworkWatcherExtensionPacket capture requires a virtual machine extension AzureNetworkWatcherExtension. 有关在 Windows VM 上安装扩展的信息,请访问适用于 Windows 的 Azure 网络观察程序代理虚拟机扩展;有关 Linux VM 的信息,请访问适用于 Linux 的 Azure 网络观察程序代理虚拟机扩展For installing the extension on a Windows VM visit Azure Network Watcher Agent virtual machine extension for Windows and for Linux VM visit Azure Network Watcher Agent virtual machine extension for Linux.

安装 VM 扩展Install VM extension

步骤 1Step 1

$VM = Get-AzVM -ResourceGroupName testrg -Name VM1

步骤 2Step 2

以下示例检索运行 Set-AzVMExtension cmdlet 所需的扩展信息。The following example retrieves the extension information needed to run the Set-AzVMExtension cmdlet. 此 cmdlet 在来宾虚拟机上安装数据包捕获代理。This cmdlet installs the packet capture agent on the guest virtual machine.

备注

Set-AzVMExtension cmdlet 可能需要几分钟才能完成。The Set-AzVMExtension cmdlet may take several minutes to complete.

对于 Windows 虚拟机:For Windows virtual machines:

$AzureNetworkWatcherExtension = Get-AzVMExtensionImage -Location chinanorth -PublisherName Microsoft.Azure.NetworkWatcher -Type NetworkWatcherAgentWindows -Version 1.4.585.2
$ExtensionName = "AzureNetworkWatcherExtension"
Set-AzVMExtension -ResourceGroupName $VM.ResourceGroupName  -Location $VM.Location -VMName $VM.Name -Name $ExtensionName -Publisher $AzureNetworkWatcherExtension.PublisherName -ExtensionType $AzureNetworkWatcherExtension.Type -TypeHandlerVersion $AzureNetworkWatcherExtension.Version.Substring(0,3)

对于 Linux 虚拟机:For Linux virtual machines:

$AzureNetworkWatcherExtension = Get-AzVMExtensionImage -Location chinanorth -PublisherName Microsoft.Azure.NetworkWatcher -Type NetworkWatcherAgentLinux -Version 1.4.13.0
$ExtensionName = "AzureNetworkWatcherExtension"
Set-AzVMExtension -ResourceGroupName $VM.ResourceGroupName  -Location $VM.Location -VMName $VM.Name -Name $ExtensionName -Publisher $AzureNetworkWatcherExtension.PublisherName -ExtensionType $AzureNetworkWatcherExtension.Type -TypeHandlerVersion $AzureNetworkWatcherExtension.Version.Substring(0,3)

以下示例是运行 Set-AzVMExtension cmdlet 后的成功响应。The following example is a successful response after running the Set-AzVMExtension cmdlet.

RequestId IsSuccessStatusCode StatusCode ReasonPhrase
--------- ------------------- ---------- ------------
                         True         OK OK   

步骤 3Step 3

为了确保安装代理,请运行 Get-AzVMExtension cmdlet 并向其传递虚拟机名称和扩展名称。To ensure that the agent is installed, run the Get-AzVMExtension cmdlet and pass it the virtual machine name and the extension name.

Get-AzVMExtension -ResourceGroupName $VM.ResourceGroupName  -VMName $VM.Name -Name $ExtensionName

以下示例是运行 Get-AzVMExtension 后的响应的实例The following sample is an example of the response from running Get-AzVMExtension

ResourceGroupName       : testrg
VMName                  : testvm1
Name                    : AzureNetworkWatcherExtension
Location                : chinaeast
Etag                    : null
Publisher               : Microsoft.Azure.NetworkWatcher
ExtensionType           : NetworkWatcherAgentWindows
TypeHandlerVersion      : 1.4
Id                      : /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testrg/providers/Microsoft.Compute/virtualMachines/testvm1/
                          extensions/AzureNetworkWatcherExtension
PublicSettings          : 
ProtectedSettings       : 
ProvisioningState       : Succeeded
Statuses                : 
SubStatuses             : 
AutoUpgradeMinorVersion : True
ForceUpdateTag          : 

启动数据包捕获Start a packet capture

完成前面的步骤后,数据包捕获代理将安装在虚拟机上。Once the preceding steps are complete, the packet capture agent is installed on the virtual machine.

步骤 1Step 1

下一步是检索网络观察程序实例。The next step is to retrieve the Network Watcher instance. 将此变量传递给步骤 4 中的 New-AzNetworkWatcherPacketCapture cmdlet。This variable is passed to the New-AzNetworkWatcherPacketCapture cmdlet in step 4.

$networkWatcher = Get-AzNetworkWatcher  | Where {$_.Location -eq "chinaeast" }

步骤 2Step 2

检索存储帐户。Retrieve a storage account. 此存储帐户用于存储数据包捕获文件。This storage account is used to store the packet capture file.

$storageAccount = Get-AzStorageAccount -ResourceGroupName testrg -Name testrgsa123

步骤 3Step 3

可以使用筛选器来限制数据包捕获存储的数据。Filters can be used to limit the data that is stored by the packet capture. 以下示例设置两个筛选器。The following example sets up two filters. 第一个筛选器仅收集从本地 IP 10.0.0.3 发往目标端口 20、80 和 443 的传出 TCP 流量。One filter collects outgoing TCP traffic only from local IP 10.0.0.3 to destination ports 20, 80 and 443. 第二个筛选器仅收集 UDP 流量。The second filter collects only UDP traffic.

$filter1 = New-AzPacketCaptureFilterConfig -Protocol TCP -RemoteIPAddress "1.1.1.1-255.255.255.255" -LocalIPAddress "10.0.0.3" -LocalPort "1-65535" -RemotePort "20;80;443"
$filter2 = New-AzPacketCaptureFilterConfig -Protocol UDP

备注

可以为数据包捕获定义多个筛选器。Multiple filters can be defined for a packet capture.

步骤 4Step 4

运行 New-AzNetworkWatcherPacketCapture cmdlet 并传递在上一步骤中检索的所需值,启动数据包捕获过程。Run the New-AzNetworkWatcherPacketCapture cmdlet to start the packet capture process, passing the required values retrieved in the preceding steps.


New-AzNetworkWatcherPacketCapture -NetworkWatcher $networkWatcher -TargetVirtualMachineId $vm.Id -PacketCaptureName "PacketCaptureTest" -StorageAccountId $storageAccount.id -TimeLimitInSeconds 60 -Filter $filter1, $filter2

以下示例是运行 New-AzNetworkWatcherPacketCapture cmdlet 后的预期输出。The following example is the expected output from running the New-AzNetworkWatcherPacketCapture cmdlet.

Name                    : PacketCaptureTest
Id                      : /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/NetworkWatcherRG/providers/Microsoft.Network/networkWatcher
                          s/NetworkWatcher_chinaeast/packetCaptures/PacketCaptureTest
Etag                    : W/"3bf27278-8251-4651-9546-c7f369855e4e"
ProvisioningState       : Succeeded
Target                  : /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testrg/providers/Microsoft.Compute/virtualMachines/testvm1
BytesToCapturePerPacket : 0
TotalBytesPerSession    : 1073741824
TimeLimitInSeconds      : 60
StorageLocation         : {
                            "StorageId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testrg/providers/Microsoft.Storage/storageA
                          ccounts/examplestorage",
                            "StoragePath": "https://examplestorage.blob.core.chinacloudapi.cn/network-watcher-logs/subscriptions/00000000-0000-0000-0000-00000
                          0000000/resourcegroups/testrg/providers/microsoft.compute/virtualmachines/testvm1/2017/02/01/packetcapture_22_42_48_238.cap"
                          }
Filters                 : [
                            {
                              "Protocol": "TCP",
                              "RemoteIPAddress": "1.1.1.1-255.255.255",
                              "LocalIPAddress": "10.0.0.3",
                              "LocalPort": "1-65535",
                              "RemotePort": "20;80;443"
                            },
                            {
                              "Protocol": "UDP",
                              "RemoteIPAddress": "",
                              "LocalIPAddress": "",
                              "LocalPort": "",
                              "RemotePort": ""
                            }
                          ]

获取数据包捕获Get a packet capture

运行 Get-AzNetworkWatcherPacketCapture cmdlet,检索当前正在运行的或已完成的数据包捕获的状态。Running the Get-AzNetworkWatcherPacketCapture cmdlet, retrieves the status of a currently running, or completed packet capture.

Get-AzNetworkWatcherPacketCapture -NetworkWatcher $networkWatcher -PacketCaptureName "PacketCaptureTest"

以下示例是 Get-AzNetworkWatcherPacketCapture cmdlet 的输出。The following example is the output from the Get-AzNetworkWatcherPacketCapture cmdlet. 以下示例是捕获完成后的输出结果。The following example is after the capture is complete. PacketCaptureStatus 值为“已停止”,StopReason 为 TimeExceeded。The PacketCaptureStatus value is Stopped, with a StopReason of TimeExceeded. 此值显示数据包捕获已成功完成,并已运行了限定的时间。This value shows that the packet capture was successful and ran its time.

Name                    : PacketCaptureTest
Id                      : /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/NetworkWatcherRG/providers/Microsoft.Network/networkWatcher
                          s/NetworkWatcher_chinaeast/packetCaptures/PacketCaptureTest
Etag                    : W/"4b9a81ed-dc63-472e-869e-96d7166ccb9b"
ProvisioningState       : Succeeded
Target                  : /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testrg/providers/Microsoft.Compute/virtualMachines/testvm1
BytesToCapturePerPacket : 0
TotalBytesPerSession    : 1073741824
TimeLimitInSeconds      : 60
StorageLocation         : {
                            "StorageId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/testrg/providers/Microsoft.Storage/storageA
                          ccounts/examplestorage",
                            "StoragePath": "https://examplestorage.blob.core.chinacloudapi.cn/network-watcher-logs/subscriptions/00000000-0000-0000-0000-00000
                          0000000/resourcegroups/testrg/providers/microsoft.compute/virtualmachines/testvm1/2017/02/01/packetcapture_22_42_48_238.cap"
                          }
Filters                 : [
                            {
                              "Protocol": "TCP",
                              "RemoteIPAddress": "1.1.1.1-255.255.255",
                              "LocalIPAddress": "10.0.0.3",
                              "LocalPort": "1-65535",
                              "RemotePort": "20;80;443"
                            },
                            {
                              "Protocol": "UDP",
                              "RemoteIPAddress": "",
                              "LocalIPAddress": "",
                              "LocalPort": "",
                              "RemotePort": ""
                            }
                          ]
CaptureStartTime        : 2/1/2017 10:43:01 PM
PacketCaptureStatus     : Stopped
StopReason              : TimeExceeded
PacketCaptureError      : []

停止数据包捕获Stop a packet capture

运行 Stop-AzNetworkWatcherPacketCapture cmdlet 后,如果捕获会话正在进行,它将停止。By running the Stop-AzNetworkWatcherPacketCapture cmdlet, if a capture session is in progress it is stopped.

Stop-AzNetworkWatcherPacketCapture -NetworkWatcher $networkWatcher -PacketCaptureName "PacketCaptureTest"

备注

该 cmdlet 在当前正在运行的捕获会话或已停止的现有会话中运行时,将不返回任何响应。The cmdlet returns no response when ran on a currently running capture session or an existing session that has already stopped.

删除数据包捕获Delete a packet capture

Remove-AzNetworkWatcherPacketCapture -NetworkWatcher $networkWatcher -PacketCaptureName "PacketCaptureTest"

备注

删除数据包捕获不会删除存储帐户中的文件。Deleting a packet capture does not delete the file in the storage account.

下载数据包捕获Download a packet capture

完成数据包捕获会话后,可以将捕获文件上传到 blob 存储或 VM 上的本地文件。Once your packet capture session has completed, the capture file can be uploaded to blob storage or to a local file on the VM. 数据包捕获的存储位置是在创建会话时定义的。The storage location of the packet capture is defined at creation of the session. 用于访问这些保存到存储帐户的捕获文件的便利工具是 Azure 存储资源管理器,下载地址为: https://storageexplorer.com/A convenient tool to access these capture files saved to a storage account is Azure Storage Explorer, which can be downloaded here: https://storageexplorer.com/

如果指定了存储帐户,则数据包捕获文件将保存到以下位置的存储帐户:If a storage account is specified, packet capture files are saved to a storage account at the following location:

https://{storageAccountName}.blob.core.chinacloudapi.cn/network-watcher-logs/subscriptions/{subscriptionId}/resourcegroups/{storageAccountResourceGroup}/providers/microsoft.compute/virtualmachines/{VMName}/{year}/{month}/{day}/packetCapture_{creationTime}.cap

后续步骤Next steps

查看创建警报触发的数据包捕获,了解如何利用虚拟机警报自动执行数据包捕获Learn how to automate packet captures with Virtual machine alerts by viewing Create an alert triggered packet capture

访问查看“IP 流验证”,了解是否允许某些流量传入和传出 VMFind if certain traffic is allowed in or out of your VM by visiting Check IP flow verify