geoip输出示例
geoip2.models.City({'city': {'geoname_id': 1796236, 'names': {'de': 'Shanghai', 'en': 'Shanghai', 'es': 'Shanghai', 'fr': 'Shanghai', 'ja': '上海', 'pt-BR': 'Xangai', 'ru': 'Шанхай', 'zh-CN': '上海'}},
'continent': {'code': 'AS', 'geoname_id': 6255147, 'names': {'de': 'Asien', 'en': 'Asia', 'es': 'Asia', 'fr': 'Asie', 'ja': 'アジア', 'pt-BR': 'Ásia', 'ru': 'Азия', 'zh-CN': '亚洲'}},
'country': {'geoname_id': 1814991, 'iso_code': 'CN', 'names': {'de': 'China', 'en': 'China', 'es': 'China', 'fr': 'Chine', 'ja': '中国', 'pt-BR': 'China', 'ru': 'Китай', 'zh-CN': '中国'}},
'location': {'accuracy_radius': 50, 'latitude': 31.0456, 'longitude': 121.3997, 'time_zone': 'Asia/Shanghai'},
'registered_country': {'geoname_id': 1814991, 'iso_code': 'CN', 'names': {'de': 'China', 'en': 'China', 'es': 'China', 'fr': 'Chine', 'ja': '中国', 'pt-BR': 'China', 'ru': 'Китай', 'zh-CN': '中国'}},
'subdivisions': [{'geoname_id': 1796231, 'iso_code': '31', 'names': {'en': 'Shanghai', 'fr': 'Municipalité de Shanghai', 'pt-BR': 'Xangai', 'zh-CN': '上海'}}], 'traits': {'ip_address': '202.120.234.116', 'prefix_len': 21}}, ['en'])
python 代码
# coding=utf-8
import geoip2.database
reader = geoip2.database.Reader('./GeoLite2-City.mmdb')
# Open a file
fo = open("ip.txt", "r")
Lines = fo.readlines()
fw = open("ipoutput.txt","w+")
count = 0
# Strips the newline character
for line in Lines:
try:
line = line.strip()
response = reader.city(line)
if 'zh-CN' in response.country.names and 'zh-CN' in response.city.names:
print(line, response.country.names['zh-CN'], "-", response.city.names['zh-CN'])
fw.write(line+" " + response.country.names['zh-CN'] + "-"+ response.city.names['zh-CN'] + "\r\n")
elif 'zh-CN' in response.country.names:
print(line, response.country.names['zh-CN'])
fw.write(line+" " + response.country.names['zh-CN'] + "\r\n")
else:
print(line, "NA")
fw.write(line + " " + "NA\r\n")
except geoip2.errors.AddressNotFoundError:
print(line, "NA")
fw.write(line + " " + "NA\r\n")
except ValueError:
print(line, "NA")
fw.write(line + " " + "NA\r\n")
# Close opend file
fo.close()
fw.close()
输出
60.12.155.35 中国 - 杭州
60.12.155.35 中国 - 杭州
222.95.18.203 中国 - 南京
222.95.18.203 中国 - 南京
114.80.11.230 中国 - 上海
218.79.7.219 中国 - 上海
218.79.7.219 中国 - 上海
218.79.7.219 中国 - 上海
GeoLite2-City.mmdb 包下载地址 或者官网 https://dev.maxmind.com/geoip/geoip2/geolite2/