netstat -b 相当于 Powershell

问题描述 投票:0回答:1

我正在寻找与用 Powershell 编写的

netstat -b
等效的内容。

微软写道:

显示创建每个连接或侦听端口所涉及的可执行文件。在某些情况下,众所周知的可执行文件托管多个独立组件,在这些情况下,会显示创建连接或侦听端口所涉及的组件序列。在这种情况下,可执行文件名称位于底部的 [] 中,顶部是它调用的组件,依此类推,直到到达 TCP/IP。请注意,此选项可能非常耗时,并且除非您有足够的权限,否则将会失败。

https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/netstat

例如EventLog监听端口显示为

netstat -anb
,表示进程名称为
svchost.exe
,调用组件为
EventLog

  TCP    0.0.0.0:49665          0.0.0.0:0              LISTENING
  EventLog
  [svchost.exe]

这个Powershell函数输出所有监听进程:

function Get-ListeningProcesses {

    Get-NetTCPConnection -State Listen |
    ForEach-Object {
        $ProcessName = (Get-Process -Id $_.OwningProcess).ProcessName
        [PSCustomObject]@{
            LocalAddress = $_.LocalAddress
            LocalPort = $_.LocalPort
            OwningProcess = $_.OwningProcess
            ProcessName = $ProcessName
        }
    }
}

输出将是:

LocalAddress LocalPort OwningProcess ProcessName
------------ --------- ------------- -----------
...
::               49665          1412 svchost    
...

但是如何获取启动的组件

svchost.exe

powershell netstat
1个回答
0
投票

不完全是我正在寻找的东西,但它满足我现在的需求。但下面的脚本列出了所有公共监听进程,包括命令行。

function Get-ListeningProcesses {

    Get-NetTCPConnection -State Listen | Where-Object {($_.LocalAddress -eq "::" -or $_.LocalAddress -eq "0.0.0.0")} |
    ForEach-Object {
        $ProcessId = $_.OwningProcess
        $ProcessName = (Get-Process -Id $_.OwningProcess).ProcessName
        $CommandLine = (Get-WmiObject Win32_process -filter "ProcessId = '$ProcessId'").CommandLine
        [PSCustomObject]@{
            LocalAddress = $_.LocalAddress
            LocalPort = $_.LocalPort
            RemoteAddress = $_.RemoteAddress
            RemotePort = $_.RemotePort
            OwningProcess = $_.OwningProcess
            ProcessName = $ProcessName
            CommandLine = $CommandLine
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.