如何使用netstat -b从.exe文件中查找IP

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

所以我正在寻找一种可以使用 netstat -b 和 findstr 的方法。我尝试在 cmd 中使用它,如下所示:

netstat -b | findstr "chrome"

但这只是给我输出

 [chrome.exe]
 [chrome.exe]
 [chrome.exe]
 [chrome.exe]
 [chrome.exe]
 [chrome.exe]

我想获取 IP 地址作为“chrome.exe”中的输出

cmd findstr netstat
3个回答
1
投票

这可以通过包含以下代码的批处理文件来完成:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "FileName=chrome.exe"
set "FoundExecutable="
for /F "tokens=1,2 delims=[] " %%G in ('%SystemRoot%\System32\netstat.exe -b 2^>nul') do (
    if /I "%%G" == "%FileName%" (
        set "FoundExecutable=1"
    ) else if /I "%%~xG" == ".exe" (
        set "FoundExecutable="
    ) else if defined FoundExecutable if "%%G" == "TCP" (
        echo %FileName% %%H
    )
)
endlocal

要了解所使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完整、仔细地阅读每个命令显示的帮助页面。

  • echo /?
  • endlocal /?
  • for /?
  • if /?
  • netstat /?
  • set /?
  • setlocal /?

阅读有关 使用命令重定向运算符的 Microsoft 文档,了解

2>nul
的说明。重定向运算符
>
必须在
FOR
命令行上使用插入符 ^ 进行转义,以便在 Windows 命令解释器在执行命令 FOR(执行嵌入的
netstat
命令行)之前处理此命令行时将其解释为文字字符使用在后台启动的单独命令进程。


0
投票

如果 powershell 适合您,则命令非常简单:

Get-NetTCPConnection -OwningProcess $(get-process chrome | % { $_.Id }) -ErrorAction SilentlyContinue

使用此命令,您可以按进程名称获取所有 PID:

get-process chrome | % { $_.Id }

然后您可以使用子 shell 按 PID 过滤

Get-NetTCPConnection
(powershell 的 netstat 替代方案)。

并非所有 Chrome 进程都建立了 TCP 连接:要获得干净的输出

ErrorAction
可以设置为
SilentlyContinue


0
投票

带 -b 选项的 netstat 显示 IP 后面的文件名

例如:

TCP 0.0.0.0:123 0.0.0.0:0 LISTENING
child_process_name
[parent_process_name.exe]

正如文档所说:

-b 显示创建每个连接或侦听端口所涉及的可执行文件。在某些情况下,众所周知的可执行文件托管多个 独立的组件,在这些情况下组件的顺序 显示参与创建连接或侦听端口的信息。在 这种情况可执行文件名称位于底部的[]中,顶部是 它调用的组件,依此类推,直到达到 TCP/IP

因此,Mofi 脚本无法正常工作

因此,基于Mofi脚本,我制作了能够正确显示文件名对应IP的脚本:

@echo off

setlocal EnableExtensions EnableDelayedExpansion

set "FileName=chrome.exe"
set "FoundExecutable="
set "IP="

for /F "tokens=1,2,3 delims=[] " %%I in ('netstat -abn 2^>nul') do (
    if "%%I" == "TCP" (
        set "IP=%%J"
        if "%%J" == "::" (
            set "IP=[%%J]%%K"
        ) else (
            set "IP=%%J"
        )
    ) else if /I "%%I" == "%FileName%" (
        set "FoundExecutable=1"
    ) else if /I "%%~xI" == ".exe" (
        call :reset
    )
    
    if defined IP if defined FoundExecutable (
        echo %FileName% !IP!
        call :reset
    )
)

:reset
set "IP="
set "FoundExecutable="
goto :eof

endlocal
© www.soinside.com 2019 - 2024. All rights reserved.