Batch - Parsing the output of Tracert

2019-05-23 14:20发布

i would like to ask for some help with the output of tracert in windows, ie i have this output :

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 
....

and i would like to produce a file that contains only the X.X.X.X or as an intermediate step to get there, only the lines of tracer that actually contain IPs. Ie :

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

I ve tried this through a batch file :

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

but instead of the desired output i get only :

Y.Y.Y.Y

I ve also tried calling on binaries from cygwin to do this, ie :

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

but that doesnt work either. Can anyone help? Thanks in advance.

2条回答
叼着烟拽天下
2楼-- · 2019-05-23 15:04

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

查看更多
我只想做你的唯一
3楼-- · 2019-05-23 15:06

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.
查看更多
登录 后发表回答