2321e21 发表于 2015-7-9 09:07:39

python版trace命令显示归属地

无论是windows还是linux系统的traceroute命令都不能显示归属地,在实际的网络维护中,这些追踪路由的归属地址也是很重要的信息,来帮助我们定位问题发生的地方。以下为python写的一个脚本来显示归属地。也方便自己的记忆和日后的使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/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.decode('gbk')
    return location
if len(sys.argv) < 2:
    print "Usage: %s {hostname|ip}" % sys.argv
    sys.exit()
else:
    host = sys.argv
system_name = platform.dist()
if system_name == 'redhat':
    trace_cmd = '/bin/traceroute'
elif system_name == 'Ubuntu':
    trace_cmd = '/usr/sbin/traceroute'
try:
    p = subprocess.Popen(,stdout=subprocess.PIPE)
    while True:
      line = p.stdout.readline()
      if not line:
            break
      if re.match("^..*(.*).*",line):
            try:
                ip = line.split('(').split(')')
               
                print line,getlocation(ip)
            except IndexError,e:
                print line,
      else:
            print line,
except (KeyboardInterrupt,SystemExit):
    sys.exit()




由于自己的网络环境在系统判断上没有加入windows,后续可以其他朋友们添加了。另外我也写了一个windows版本的。欢迎大家一起交流
页: [1]
查看完整版本: python版trace命令显示归属地