监控网络对应进程

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
Get-Date -Format "MM/dd/yyyy HH:mm"
write-host '如需结束: 请按 Ctrl+C'
write-host '日志文件:NetTCPConnection.csv'
write-host '正在捕获网络连接中...'
Remove-Item NetTCPConnection.txt -ErrorAction 0


function netinfo {
$Processes = @{}
$logfile='NetTCPConnection.csv'
Get-Process -IncludeUserName | ForEach-Object {
$Processes[$_.Id] = $_
}

$r=Get-NetTCPConnection -RemotePort 135,445,139 -ErrorAction 0 |
Select-Object State, RemoteAddress,
RemotePort,
@{Name="Time"; Expression={ Get-Date -Format "MM/dd/yyyy HH:mm" }},
@{Name="PID"; Expression={ $_.OwningProcess }},
@{Name="ProcessName"; Expression={ $Processes[[int]$_.OwningProcess].ProcessName }},
@{Name="UserName"; Expression={ $Processes[[int]$_.OwningProcess].UserName }},
@{Name="EXEC_PATH"; Expression={ $Processes[[int]$_.OwningProcess].Path }}


if($r){

# write-host '------------------------------------------------------------'|Out-File $logfile -Append |Out-Null
write-host '获取到数据.'
#Get-Date -Format "获取信息时间: MM/dd/yyyy HH:mm" | Out-File $logfile -Append |Out-Null
#$r| Out-File $logfile -Append |Out-Null
$r|export-csv -Path $logfile -Append -NoTypeInformation|Out-Null
#write-host '------------------------------------------------------------'|Out-File $logfile -Append |Out-Null

}
}

while(1){
netinfo
sleep 5
}