- 论坛徽章:
- 0
|
用 python 寫了一個, 但速度不快- #!/usr/bin/env python
- # True 如果 ip 在 range 裡, otherwise False
- def compareIp(rangeFrom, rangeTo, ip):
- # 把 ip 轉換成數字串, 那就可以用來比較大小
- # ex: '12.40.255.1' ----> '012040255001'
- rangeFrom = ''.join(['%03d' % int(i) for i in rangeFrom.split('.')])
- rangeTo = ''.join(['%03d' % int(i) for i in rangeTo.split('.')])
- ip = ''.join(['%03d' % int(i) for i in ip.split('.')])
-
- return rangeFrom <= ip <= rangeTo
- def showIpAdderss(source_file, address_file):
- all_source = open(source_file)
- all_address = open(address_file)
- # 把 source file 裡的 ip 都存到 addresss
- # address = ['0.12.1.4', '23.53.36.2', '123.23.255.2']
- address = [ip.strip() for ip in all_address.readlines()]
-
- # delete 所有不必要的 space, newline
- # 得到: source = ['4.53.3.1', '4.53.255.255', '美國', 'CZ88.NET']
- source = [ip.strip() for ip in all_source.readline().split(' ') if ip]
- # 每次只讀一行 data file
- while source:
- # 檢查 address 裡每一個 ip
- for ip in address:
- if compareIp(source[0], source[1], ip):
- # 如果 pi 在 range 裡, 打印而且從 address 裡拿掉,
- # 下次不會再檢查同樣一個 ip
- print '%s\t%s\t%s' % (ip, source[2], source[3])
- address.remove(ip)
- source = [ip.strip() for ip in all_source.readline().split(' ') if ip]
- all_source.close()
- all_address.close()
- if __name__=='__main__':
- import sys
- if len(sys.argv) != 3:
- print 'Usage: python ipLocation.py <ip locations sources> <ip addresses>'
- sys.exit(0)
- showIpAdderss(sys.argv[1], sys.argv[2])
复制代码 data.txt = ip地址库
source.txt = ip文本
Kyles-MacBook:Test kyle$ python ipLocation.py data.txt source.txt
4.19.79.64 美国 CZ88.NET
23.12.2.9 IANA CZ88.NET
56.77.4.54 美国 北卡罗来纳(美国邮政局)
61.132.92.115 江苏省常州市 电信ADSL
61.132.122.248 江苏省苏州市 苏州工业职业技术学院苏高工校区
90.200.213.255 英国 CZ88.NET
132.23.49.12 CZ88.NET
156.233.12.86 未知物理地址 CZ88.NET
177.23.123.94 CZ88.NET
187.123.42.66 CZ88.NET
202.19.235.23 日本 CZ88.NET
211.23.255.8 台湾省 中华电 |
|