【问题标题】:Batch - Parsing the output of Tracert批处理 - 解析 Tracert 的输出
【发布时间】:2016-12-28 00:03:48
【问题描述】:

我想就 Windows 中的 tracert 输出寻求一些帮助,即我有这个输出:

Tracing route to Y.Y.Y.Y over a maximum of 30 hops

1     1 ms     1 ms     1 ms  X.X.X.X 
2   103 ms    71 ms    22 ms  X.X.X.X 
3    35 ms    51 ms    35 ms  X.X.X.X 
....

我想生成一个仅包含 X.X.X.X 的文件,或者作为到达那里的中间步骤,仅包含实际包含 IP 的跟踪器行。即:

X.X.X.X
X.X.X.X
X.X.X.X

我已经通过批处理文件尝试过:

for /f "tokens=8" %%a in ('tracert -4 -d 8.8.8.8^|find "ms"') do (
    @echo %%a >D:\panagos\desktop\ips.txt
)

但我得到的不是所需的输出:

Y.Y.Y.Y

我也尝试过从 cygwin 调用二进制文件来执行此操作,即:

D:\path\to\slash\bin\awk '{ print $8 }' filein > fileout

但这也不起作用。任何人都可以帮忙吗?提前致谢。

【问题讨论】:

  • but that doesnt work either 到底出了什么问题?在 linux 上,我尝试了 awk '/ ms/ {print $8}' filein,这应该可以提供您预期的输出

标签: parsing batch-file awk traceroute


【解决方案1】:

使用以下批处理文件:

GetIPs.cmd:

@echo off
rem skip 2 header lines
rem ip address is the 8th token
for /f "skip=2 tokens=8" %%d in ('tracert -4 -d 8.8.8.8') do (
  echo %%d
  )>>ips.txt
endlocal

示例:

F:\test>tracert -4 -d 8.8.8.8

Tracing route to 8.8.8.8 over a maximum of 30 hops

  1    <1 ms    <1 ms    <1 ms  192.168.42.129
  2     *        *        *     Request timed out.
  3    53 ms    48 ms    48 ms  10.248.29.129
  4    46 ms    48 ms    48 ms  10.247.82.25
  5    55 ms    48 ms    48 ms  10.247.82.6
  6    55 ms    48 ms    48 ms  10.247.82.9
  7    46 ms    48 ms    48 ms  10.247.82.18
  8    55 ms    48 ms    48 ms  87.237.20.236
  9    56 ms    59 ms    48 ms  87.237.20.85
 10    56 ms    58 ms    47 ms  74.125.52.216
 11    55 ms    48 ms    51 ms  216.239.41.179
 12    58 ms    48 ms    59 ms  216.239.57.83
 13    58 ms    59 ms    48 ms  8.8.8.8

Trace complete.

F:\test>GetIPs

F:\test>type ips.txt
192.168.42.129
10.248.29.129
10.247.82.25
10.247.82.6
10.247.82.9
10.247.82.18
87.237.20.236
87.237.20.85
74.125.52.216
216.239.41.179
216.239.57.83
8.8.8.8

进一步阅读

【讨论】:

    【解决方案2】:

    阅读Redirection

    command > filename        Redirect command output to a file
    command >> filename       APPEND into a file
    

    使用任一

    type NUL >D:\panagos\desktop\ips.txt
    for /f "tokens=8" %%a in ('tracert -4 -d 8.8.8.8^|find "ms"') do (
        @echo %%a >>D:\panagos\desktop\ips.txt
    )
    

    或(更好)

    @echo OFF
    >D:\panagos\desktop\ips.txt (
        for /f "tokens=8" %%a in ('tracert -4 -d 8.8.8.8^|find "ms"') do (
            echo %%a
        )
    )
    

    还请注意,您的脚本隐藏了 无法访问 主机,请参阅下一个示例中的第 12 跳只有 7 个令牌:

    ==> tracert -d 8.8.8.8
    
    Tracing route to 8.8.8.8 over a maximum of 30 hops
    
     …
     11    36 ms    44 ms    36 ms  108.170.234.149
     12     *        *        *     Request timed out.
     13    36 ms    36 ms    35 ms  8.8.8.8
    
    Trace complete.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多