81 lines
2.4 KiB
Python
81 lines
2.4 KiB
Python
|
|
"""
|
|||
|
|
GeoIP2 IP归属地查询测试脚本
|
|||
|
|
|
|||
|
|
使用方法:
|
|||
|
|
1. 安装依赖:pip install geoip2
|
|||
|
|
2. 下载数据库:https://dev.maxmind.com/geoip/geoip2/geolite2/
|
|||
|
|
3. 运行测试:python test_geoip.py
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
import os
|
|||
|
|
import sys
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
import geoip2.database
|
|||
|
|
except ImportError:
|
|||
|
|
print("请先安装 geoip2: pip install geoip2")
|
|||
|
|
sys.exit(1)
|
|||
|
|
|
|||
|
|
DB_PATH = os.path.join(os.path.dirname(__file__), "GeoLite2-City.mmdb")
|
|||
|
|
|
|||
|
|
TEST_IPS = [
|
|||
|
|
"8.8.8.8", # Google DNS (美国)
|
|||
|
|
"114.114.114.114", # 114 DNS (中国南京)
|
|||
|
|
"223.5.5.5", # 阿里DNS (中国杭州)
|
|||
|
|
"1.1.1.1", # Cloudflare DNS (澳大利亚)
|
|||
|
|
"119.29.29.29", # 腾讯DNS (中国)
|
|||
|
|
]
|
|||
|
|
|
|||
|
|
|
|||
|
|
def get_location(reader, ip: str) -> dict:
|
|||
|
|
try:
|
|||
|
|
response = reader.city(ip)
|
|||
|
|
return {
|
|||
|
|
"ip": ip,
|
|||
|
|
"country": response.country.name,
|
|||
|
|
"country_code": response.country.iso_code,
|
|||
|
|
"region": response.subdivisions.most_specific.name if response.subdivisions else None,
|
|||
|
|
"city": response.city.name,
|
|||
|
|
"latitude": response.location.latitude,
|
|||
|
|
"longitude": response.location.longitude,
|
|||
|
|
"timezone": response.location.time_zone,
|
|||
|
|
}
|
|||
|
|
except geoip2.errors.AddressNotFoundError:
|
|||
|
|
return {"ip": ip, "error": "IP未在数据库中找到"}
|
|||
|
|
except Exception as e:
|
|||
|
|
return {"ip": ip, "error": str(e)}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
if not os.path.exists(DB_PATH):
|
|||
|
|
print(f"数据库文件不存在: {DB_PATH}")
|
|||
|
|
print("请从 https://dev.maxmind.com/geoip/geoip2/geolite2/ 下载 GeoLite2-City.mmdb")
|
|||
|
|
return
|
|||
|
|
|
|||
|
|
print(f"加载数据库: {DB_PATH}")
|
|||
|
|
reader = geoip2.database.Reader(DB_PATH)
|
|||
|
|
|
|||
|
|
print("\n" + "=" * 60)
|
|||
|
|
print("IP归属地查询测试")
|
|||
|
|
print("=" * 60)
|
|||
|
|
|
|||
|
|
for ip in TEST_IPS:
|
|||
|
|
result = get_location(reader, ip)
|
|||
|
|
if "error" in result:
|
|||
|
|
print(f"\n{ip}: {result['error']}")
|
|||
|
|
else:
|
|||
|
|
print(f"\n{ip}:")
|
|||
|
|
print(f" 国家: {result['country']} ({result['country_code']})")
|
|||
|
|
print(f" 地区: {result['region'] or '未知'}")
|
|||
|
|
print(f" 城市: {result['city'] or '未知'}")
|
|||
|
|
print(f" 坐标: {result['latitude']}, {result['longitude']}")
|
|||
|
|
print(f" 时区: {result['timezone']}")
|
|||
|
|
|
|||
|
|
reader.close()
|
|||
|
|
print("\n" + "=" * 60)
|
|||
|
|
print("测试完成")
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
main()
|