-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNetmonCircular.ps1
201 lines (193 loc) · 7.35 KB
/
NetmonCircular.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
[CmdletBinding()]
param (
[Parameter()] [string] $OutPath = 'C:\NetCap',
[Parameter()] [int] $NumOfFile = 10,
[Parameter()] [int] $Size = 512,
[Parameter()] [string] $CaptureFilter = '',
[Parameter()] [int] $ParserId = 2,
[Parameter()] [int] $PullInterval = 1
)
function StopNmcap
{
param(
[Parameter()] [Object] $NmProcess
)
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class StartActivateProgramClass {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
}
"@
if ($NmProcess)
{
$NmHandle = $NmProcess.Parent.MainWindowHandle
[void] [StartActivateProgramClass]::SetForegroundWindow($NmHandle)
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait('X')
}
if (!$NmProcess.HasExited)
{
Write-Host 'Automatic Stop Failed!' -ForegroundColor White -BackgroundColor DarkYellow
Write-Host 'Switch to NMCap window and press X to stop the capture manually' -ForegroundColor White -BackgroundColor DarkYellow
}
}
if (!(Test-Path "$env:ProgramFiles\Microsoft Network Monitor 3"))
{
Write-Host "Microsoft Network Monitor 3 Not Installed!" -ForegroundColor Red
Write-Host "Download and Install NetMon at http://go.microsoft.com/fwlink/?linkid=220643" -ForegroundColor Red
Pause
Exit
}
if (!(Get-NetAdapterBinding).ComponentID.Contains('ms_netmon'))
{
Write-Host "Microsoft Network Monitor 3 Driver is Not Bound on Any Network Adapter!" -ForegroundColor Red
Write-Host "Reinstall NetMon or Launch the Script as Administrator and Try Again" -ForegroundColor Red
Pause
Exit
}
if (!(Test-Path $OutPath))
{
try
{
mkdir $OutPath | Out-Null
}
catch
{
Write-Host "Output path cannot be created!" -ForegroundColor Red
Pause
Exit
}
}
if ((Get-ChildItem $OutPath\*.cap).Count -ne 0)
{
while ($true)
{
$Confirm = Read-Host "Existing CAP files in destination folder. Backup the files or remove? B/R"
if ($Confirm -eq "B" -or $Confirm -eq "b")
{
$BackupFolder = $OutPath + '\CapBackup_' + (Get-Date -Format 'yyyy-MM-dd_hhmmss')
mkdir $BackupFolder | Out-Null
Move-Item $OutPath\*.cap $BackupFolder
"Backed up files to $BackupFolder `n"
break
}
if ($Confirm -eq "R" -or $Confirm -eq "r")
{
Remove-Item $OutPath\*.cap
"Removed files`n"
break
}
}
}
Write-Host "NetMon Circular Capture"
Write-Host "-------------------------------------------------"
Write-Host " > Output Path: $OutPath"
Write-Host " > Num of Files to be Kept: $NumOfFile"
Write-Host " > Size of Each File: $Size MB"
Write-Host " > Capture Filter: $CaptureFilter"
Write-Host " > Parser Profile ID: $ParserId"
Write-Host " > Pull Interval: $PullInterval sec"
Write-Host "-------------------------------------------------"
Write-Host ""
Write-Host "Press Enter to Start Capture." -ForegroundColor White -BackgroundColor DarkGreen
Write-Host "Press F12 to Stop Capture. " -ForegroundColor White -BackgroundColor DarkGreen
Read-Host
$Argument = "/UseProfile $ParserId /Network * /Capture $CaptureFilter /file $OutPath\NetTraceNM.chn:" + $Size + "M /StopWhen /Frame IPv4.Address == 4.3.2.1 AND ICMP /TerminateWhen /KeyPress X"
if (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
$Argument += ' /CaptureProcesses'
}
else
{
Write-Host 'Not running as Administrator, Capture Process will not be enabled.' -ForegroundColor White -BackgroundColor Yellow
}
Write-Host "Calling NetMon" -ForegroundColor White -BackgroundColor DarkGreen
Write-Host "CommandLine: $env:ProgramFiles\Microsoft Network Monitor 3\nmcap.exe $Argument" -ForegroundColor White -BackgroundColor DarkGreen
$NmcapProcess = Start-Process -FilePath "$env:ProgramFiles\Microsoft Network Monitor 3\nmcap.exe" -ArgumentList $Argument -WindowStyle Minimized -PassThru
$Continue = $true
while ($Continue)
{
if ([console]::KeyAvailable)
{
if ([System.Console]::ReadKey().Key -eq 'F12')
{
Write-Host "`nF12 Pressed. Pinging 4.3.2.1 to stop capture."
$Continue = $false
}
else
{
Write-Host "Press F12 to Stop Capture"
}
}
else
{
$TraceFiles = Get-ChildItem $OutPath\*.cap | Sort-Object -Property CreationTime
if ($TraceFiles.Count -gt $NumOfFile)
{
$Prompt = "`nPurging File: " + $TraceFiles[0]
Write-Host $Prompt -ForegroundColor Yellow
Remove-Item -Path $TraceFiles[0]
}
else
{
Write-Host '.' -NoNewline
Start-Sleep -Milliseconds ($PullInterval * 1000 - 100)
}
}
if ($NmcapProcess.HasExited)
{
Write-Host "`nNMCap Process Exited Unexpectedly! Script Terminated!" -ForegroundColor Red
Write-Host "This could be caused by an unexpected ICMP packet to/from IP address 4.3.2.1 or not running NMCap as Administrator (No bound interface is found)" -ForegroundColor Red
Pause
Exit
}
Start-Sleep -Milliseconds 100 # Key Read Interval to Save CPU Usage.
}
ping.exe 4.3.2.1 -n 5 -w 100 | Out-Null
if (!$NmcapProcess.HasExited)
{
$Warning =
"WARNING:
NetMon has NOT exited yet!
This could be caused by high volume of traffic pending process.
If forcibly terminate NetMon, there will be data lost.
If wait for NetMon finish processing, more capture files will be saved and you need to purge old captures manually."
Write-Host $Warning -ForegroundColor White -BackgroundColor DarkYellow
while ($true)
{
$ForceExit = Read-Host -Prompt "Do you want to forcibly terminate NetMon? Yes/No (Default - No)"
if (($ForceExit -eq 'yes') -or ($ForceExit -eq 'Yes'))
{
StopNmcap -NmProcess $NmcapProcess
break
}
if (($ForceExit -eq 'no') -or ($ForceExit -eq 'No') -or ($ForceExit -eq ''))
{
Write-Host "Waiting for NetMon stopping. Keep pinging 4.3.2.1. Press F12 to stop immediately."
Write-Host "WARNING: DO NOT forcibly stop this script at this stage, or you need to terminate the PING process and NMCap process manually!" -ForegroundColor White -BackgroundColor DarkYellow
$PingProcess = Start-Process 'ping.exe' -ArgumentList '4.3.2.1 -t -w 100' -WindowStyle Hidden -PassThru
while (!$NmcapProcess.HasExited)
{
if ([console]::KeyAvailable)
{
if ([System.Console]::ReadKey().Key -eq 'F12')
{
Write-Host "`nF12 Pressed. Terminate NMCap Process."
StopNmcap -NmProcess $NmcapProcess
}
}
Write-Host '.' -NoNewline
Start-Sleep -Milliseconds 1000
}
if (!$PingProcess.HasExited)
{
Stop-Process -Id $PingProcess.Id -Force
}
break
}
}
}
Start-Process $OutPath