Parsing data from traceroute command

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 10:14:33

问题


I am trying to parse the "number of hops" value from the traceroute command and output it with a bash script.

Any hints? Very new so thanks.

My script looks like this so far:

#!/bin/bash
#parse traceroute for hops and output to stdout.
echo -n "Enter a host name(like www.google.com):  "
read hostname
traceroute 2>&1 $hostname|grep "hops"
echo "number of hops are "

回答1:


Are you looking for the number of hops it took, or the "64 hops max" value? If it's the former, use tail to get the last line of output, then awk to print the first column:

traceroute "$hostname" 2>/dev/null | tail -1 | awk '{print $1}'



回答2:


The only occurrence of "hops" in traceroute output (stderr, actually) is towards the top, in the stderr "header" line:

traceroute to foo.bar.com (123.12.1.23), 30 hops max, 40 byte packets

or the like -- if that's the one line you want to grab, you might grep for "hops max," or the like in order to reduce the risk of undesired hits (should some intermediate host just happen to have "hops" in their DNS).

Is this what you mean? Is your problem grabbing this 30, the maximum number of hops, into a bash variable? If that's so, then

maxhops=`traceroute www.yahoo.com 2>&1 >/dev/null | grep "hops max" | cut -d' ' -f5`

should help -- you can use $maxhops after this (and it will be 30 in the above example).

But I suspect you mean something completely different -- clarify, maybe...?

Edit: the OP has clarified they want, not maxhops, but the actual number of hops as measured by traceroute; for that purpose,

numhops=`traceroute www.yahoo.com 2>/dev/null | tail -1 | cut -d' ' -f2`

or a simpler

numhops=`traceroute www.yahoo.com | wc -l`

should work fine!

If you do want anything fancier (or more than one result, etc) then awk as suggested in other answers is perfectly fine, but a pipeline mix of grep, tail, and cut, is quite a traditional unix-y approach, and still quite workable for simple cases (and some complex ones, but awk or perl may be more appropriate for those;-).




回答3:


traceroute www.google.com 2>/dev/null | awk 'NR==1{print $5;exit}'



回答4:


another way, where those hops not reachable (for lack of better word) are not counted

# traceroute www.yahoo.com 2>/dev/null | awk 'NR>1 && !/* * */{c++}END{print c}'
  16


来源:https://stackoverflow.com/questions/1183625/parsing-data-from-traceroute-command

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