python版trace命令顯示歸屬地

     無論是windows還是linux系統的traceroute命令都不能顯示歸屬地,在實際的網絡維護中,這些追蹤路由的歸屬地址也是很重要的信息,來幫助我們定位問題發生的地方。以下爲python寫的一個腳本來顯示歸屬地。也方便自己的記憶和日後的使用。

#!/usr/bin/python

import sys
import os
import re
import urllib2
import subprocess
import platform
def getlocation(ipaddr):
    url = "http://www.ip138.com/ips138.asp?ip=%s&action=2" % ipaddr
    u = urllib2.urlopen(url)
    s = u.read()
#Get IP Address
    ip = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',s)
#Get IP Address Location
    result = re.findall(r'(<li>.*?</li>)',s)
    location = result[0][16:-5].decode('gbk')
    return location
if len(sys.argv) < 2:
    print "Usage: %s {hostname|ip}" % sys.argv[0]
    sys.exit()
else:
    host = sys.argv[1]
system_name = platform.dist()[0]
if system_name == 'redhat':
    trace_cmd = '/bin/traceroute'
elif system_name == 'Ubuntu':
    trace_cmd = '/usr/sbin/traceroute'
try:
    p = subprocess.Popen([trace_cmd,host],stdout=subprocess.PIPE)
    while True:
        line = p.stdout.readline()
        if not line:
            break
        if re.match("^.[0-9].*(.*).*",line):
            try:
                ip = line.split('(')[1].split(')')[0]
                
                print line,getlocation(ip)
            except IndexError,e:
                print line,
        else:
            print line,
except (KeyboardInterrupt,SystemExit):
    sys.exit()

由於自己的網絡環境在系統判斷上沒有加入windows,後續可以其他朋友們添加了。另外我也寫了一個windows版本的。歡迎大家一起交流

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章