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[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()
|