|
之前追踪网络故障可能需要打开网址输入ip138等之类的网站查看问题ip归属地,这个脚本再mac/linux用来就是长期命令行操作的时候无需打开浏览器直接查询ip归属地来追踪网络归属地的小脚本,比起打开网页来直观更速度,
PS:最近对该脚本进行了改进,同时使用了ip.138,ip.cn,ip.qq查询地址,因为一方面有时候一个地址库查询未必准确的情况下,综合三者一起查询会增大命中率
- #!/usr/bin/env python
- #coding=utf-8
- '''
- 这是模仿在各种查询IP解析的网站上输入IP查询地址的过程
- '''
- #usage: python filename 8.8.8.8
- import urllib, re, sys
- class bcolors:
- HEADER = '\033[95m'
- OK_BLUE = '\033[94m'
- OK_GREEN = '\033[92m'
- WARING_YELLOW = '\033[93m'
- FAIL = '\033[36m'
- FLASHING = '\033[35m'
- CRITICAL_RED = '\033[31m'
- END = '\033[0m'
- def getip_qq(ip=sys.argv[1]):
- '''
- use QQ database
- '''
- #请求URL,以及请求解析的URL格式变化
- url = "http://ip.qq.com/cgi-bin/searchip"
- data = "searchip1=" + ip
- #不同的网站网页字符编码不同,匹配不同的内容,封装不同的编码
- html = urllib.urlopen(url, data).read().decode("gb2312")
- #查询匹配的内容
- pat = re.compile(r'<span>(.*)</span></p>')
- result = re.findall(pat, html)
- print "ip.qq.com 查询地址:"
- print ' ' + bcolors.OK_GREEN + ip + bcolors.END + " < --- > " + bcolors.WARING_YELLOW + result[0].encode("utf-8").replace(' ', '') + bcolors.END
- def getip_ip138(ip=sys.argv[1]):
- '''
- use ip138
- '''
- url = "http://ip138.com/ips1388.asp?ip=%s&action=2" % ip
- html = urllib.urlopen(url).read().decode("gb2312")
- #这是要查询匹配的内容
- string = "本站主数据:".decode("utf-8")
- # print string
- result = re.findall(string+'([^<>]+)</li>',html)
- print "ip138.com 查询地址:"
- print ' ' + bcolors.OK_GREEN + ip + bcolors.END + " < --- > " + bcolors.WARING_YELLOW + result[0].encode("utf-8").replace(' ', '') + bcolors.END
- def getip_cn(ip=sys.argv[1]):
- '''
- use ip.cn
- '''
- url = "http://ip.cn/index.php?ip=%s" % ip
- html = urllib.urlopen(url).read().decode("utf-8")
- string = "来自:".decode("utf-8")
- result = re.findall(string+'([^<>]+)</p>',html)
- print "ip.cn 查询地址:"
- print ' ' + bcolors.OK_GREEN + ip + bcolors.END + " < --- > " + bcolors.WARING_YELLOW + result[0].encode("utf-8").replace(' ', '') + bcolors.END
- if __name__ == '__main__':
- getip_qq()
- getip_ip138()
- getip_cn()
复制代码
|
|