您的位置:首页 > 编程语言 > Python开发

python版trace命令显示归属地

2015-07-08 11:22 525 查看
无论是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版本的。欢迎大家一起交流

本文出自 “技术为王” 博客,谢绝转载!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: