Batch - Parsing the output of Tracert

ⅰ亾dé卋堺 提交于 2019-12-06 10:59:38

Use the following batch file:

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

Example:

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

Further Reading

Read Redirection:

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

Use either

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
)

or (better)

@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
    )
)

Also note that your script hides unreachable hosts, see that 12th hop in next example has only 7 tokens:

==> 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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!