tengyue avatar

Python2.7 Mtr路由跟踪解析IP

tengyue

Published: 16 May 2018 › Updated: 16 May 2018Python2.7 Mtr路由跟踪解析IP

Python2.7 Mtr路由跟踪解析IP

在linux在做路由跟踪时,在某一跳出问题时,并不知道是哪里的ISP有问题,在找到中断ip后必去查该ip的ISP才知道哪里路由有问题,但是每次查找都很麻烦,所以想在得出路由跟踪ip后直接查找ip的ISP并显示出来多好啊,IP库使用taobao的API接口。

![](https://steemitimages.com/DQmWnYJAFpFwpTZvrsRwQbGVuWzVhH34G6xMGaagZURz5Ba/image.png)
[root@salt ~]# cat ip.py 
#!/usr/bin/python
import json,os,sys,socket,urllib2

ipadd=sys.argv[1]
osname=socket.gethostname()
st1='mtr -n -i 0.3 -c 10 -r -w'+' '+ ipadd+' '+'> /tmp/ipres'

def GetIp(o):
    respone=urllib2.urlopen('http://ip.taobao.com/service/getIpInfo.php?ip='+o)
    t=respone.read()
    data=json.loads(t)
    return data['data']['country'],data['data']['city'],data['data']['isp']

os.system(st1)
fp=open('/tmp/ipres')
print 'HOST: ' + osname + '           Loss%   Snt   Last   Avg  Best  Wrst StDev        ISP'
for i in fp.readlines()[1:]:
    t=i.strip()
    for p in i.strip().split()[1:2]:
        if p == '???':
            x='Forbid ICMP detect '
            print t + '    ' + x
        elif p == '`|--':
            del p
        elif p == '|--':
            del p
        else:
            z,x,y=GetIp(p)
            if z == 'IANA':
                z='internet IP'
            print t + '    ' + z + x + y
fp.close()
os.remove('/tmp/ipres')


源自:http://www.codeweblog.com/python2-7-mtr%E8%B7%AF%E7%94%B1%E8%B7%9F%E8%B8%AA%E8%A7%A3%E6%9E%90ip/

Leave Python2.7 Mtr路由跟踪解析IP to:

Written by

Read more #python posts


Best Posts From tengyue

We have not curated any of tengyue's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From tengyue