322 lines
12 KiB
Python
322 lines
12 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
GeoLite2-City 数据库下载/更新工具
|
||
|
||
用法:
|
||
# 新版 API(推荐,需 Account ID + License Key)
|
||
python download_geolite2.py --account-id 1395316 --license-key YOUR_KEY
|
||
|
||
# 旧版 API(仅 License Key,老账号可用)
|
||
python download_geolite2.py --license-key YOUR_KEY
|
||
|
||
# 通过环境变量配置
|
||
MAXMIND_ACCOUNT_ID=1395316 MAXMIND_LICENSE_KEY=xxx python download_geolite2.py
|
||
|
||
# 无 Key,走社区镜像(无需注册)
|
||
python download_geolite2.py
|
||
|
||
# 强制重新下载
|
||
python download_geolite2.py --license-key YOUR_KEY --force
|
||
|
||
获取 License Key:
|
||
1. 注册 https://www.maxmind.com/en/geolite2/signup
|
||
2. 登录后进入 Account → Manage License Keys → Generate
|
||
3. 免费账号即可,每月更新一次数据库
|
||
4. 新版 API 需要 Account ID(登录后在账号概览页可见)
|
||
"""
|
||
import argparse
|
||
import os
|
||
import sys
|
||
import tarfile
|
||
import tempfile
|
||
import time
|
||
import zipfile
|
||
from pathlib import Path
|
||
|
||
# 数据库存放路径(项目根目录)
|
||
DB_PATH = Path(__file__).parent.parent / "GeoLite2-City.mmdb"
|
||
# 记录上次更新时间的文件
|
||
STAMP_PATH = DB_PATH.with_suffix(".mmdb.update_stamp")
|
||
# 更新间隔:7 天
|
||
UPDATE_INTERVAL_DAYS = 7
|
||
|
||
# MaxMind 官方下载端点
|
||
# 新版 API(permalink,需基本认证 account_id:license_key,返回 tar.gz)
|
||
NEW_API_URL = "https://download.maxmind.com/geoip/databases/GeoLite2-City/download"
|
||
# 旧版 API(query param 传 license_key,返回 zip)
|
||
OLD_API_URL = "https://download.maxmind.com/app/geoip_download"
|
||
|
||
# 备用镜像(社区维护,无需 License Key)
|
||
# linklet-io/GeoLite.mmdb 的 download 分支有完整的 City/ASN/Country mmdb
|
||
# 通过 GitHub API 获取(raw.githubusercontent 在国内常超时,API 更稳)
|
||
MIRROR_REPO = "linklet-io/GeoLite.mmdb"
|
||
MIRROR_BRANCH = "download"
|
||
MIRROR_FILE = "GeoLite2-City.mmdb"
|
||
|
||
|
||
def _download_with_license_key(license_key: str, account_id: str = "") -> bool:
|
||
"""用 MaxMind 官方 API 下载
|
||
新版 API:基本认证 (account_id, license_key),返回 tar.gz(推荐)
|
||
旧版 API:query param 传 license_key,返回 zip(老账号兼容)
|
||
"""
|
||
import requests
|
||
|
||
# 先试新版 API(有 account_id 时优先)
|
||
if account_id:
|
||
print(f"[GeoLite2] 从 MaxMind 官方下载(新版 API, account={account_id})...")
|
||
try:
|
||
resp = requests.get(
|
||
NEW_API_URL,
|
||
params={"suffix": "tar.gz"},
|
||
auth=(account_id, license_key),
|
||
timeout=120,
|
||
stream=True,
|
||
)
|
||
if resp.status_code == 200:
|
||
return _save_tarball(resp, source="官方新版API")
|
||
else:
|
||
body = resp.text[:200]
|
||
print(f"[GeoLite2] 新版 API 返回 {resp.status_code}: {body}")
|
||
except Exception as e:
|
||
print(f"[GeoLite2] 新版 API 异常: {e}")
|
||
|
||
# 降级到旧版 API
|
||
print(f"[GeoLite2] 从 MaxMind 官方下载(旧版 API)...")
|
||
params = {
|
||
"edition_id": "GeoLite2-City",
|
||
"license_key": license_key,
|
||
"suffix": "zip",
|
||
}
|
||
try:
|
||
resp = requests.get(OLD_API_URL, params=params, timeout=120, stream=True)
|
||
if resp.status_code != 200:
|
||
body = resp.text[:200]
|
||
print(f"[GeoLite2] 旧版 API 返回 {resp.status_code}: {body}")
|
||
return False
|
||
return _save_zip(resp.content, source="官方旧版API")
|
||
except Exception as e:
|
||
print(f"[GeoLite2] 下载失败: {e}")
|
||
return False
|
||
|
||
|
||
def _save_tarball(resp, source: str = "") -> bool:
|
||
"""保存 tar.gz 响应,提取 .mmdb 文件"""
|
||
try:
|
||
with tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) as f:
|
||
for chunk in resp.iter_content(chunk_size=65536):
|
||
f.write(chunk)
|
||
tar_path = f.name
|
||
|
||
with tarfile.open(tar_path, "r:gz") as tf:
|
||
mmdb_members = [m for m in tf.getmembers() if m.name.endswith(".mmdb")]
|
||
if not mmdb_members:
|
||
print(f"[GeoLite2] tar.gz 内未找到 .mmdb 文件")
|
||
os.unlink(tar_path)
|
||
return False
|
||
with tempfile.TemporaryDirectory() as tmpdir:
|
||
tf.extract(mmdb_members[0], tmpdir)
|
||
src = Path(tmpdir) / mmdb_members[0].name
|
||
_atomic_replace(src, DB_PATH)
|
||
|
||
os.unlink(tar_path)
|
||
_write_stamp()
|
||
size_mb = DB_PATH.stat().st_size / (1024 * 1024)
|
||
print(f"[GeoLite2] 下载完成({source}): {DB_PATH} ({size_mb:.1f} MB)")
|
||
return True
|
||
except Exception as e:
|
||
print(f"[GeoLite2] 保存 tar.gz 失败: {e}")
|
||
return False
|
||
|
||
|
||
def _save_zip(content: bytes, source: str = "") -> bool:
|
||
"""保存 zip 内容,提取 .mmdb 文件"""
|
||
try:
|
||
with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as f:
|
||
f.write(content)
|
||
zip_path = f.name
|
||
|
||
with zipfile.ZipFile(zip_path, "r") as zf:
|
||
mmdb_files = [n for n in zf.namelist() if n.endswith(".mmdb")]
|
||
if not mmdb_files:
|
||
print("[GeoLite2] zip 内未找到 .mmdb 文件")
|
||
os.unlink(zip_path)
|
||
return False
|
||
with tempfile.TemporaryDirectory() as tmpdir:
|
||
zf.extract(mmdb_files[0], tmpdir)
|
||
src = Path(tmpdir) / mmdb_files[0]
|
||
_atomic_replace(src, DB_PATH)
|
||
|
||
os.unlink(zip_path)
|
||
_write_stamp()
|
||
size_mb = DB_PATH.stat().st_size / (1024 * 1024)
|
||
print(f"[GeoLite2] 下载完成({source}): {DB_PATH} ({size_mb:.1f} MB)")
|
||
return True
|
||
except Exception as e:
|
||
print(f"[GeoLite2] 保存 zip 失败: {e}")
|
||
return False
|
||
|
||
|
||
def _atomic_replace(src: Path, dst: Path):
|
||
"""原子替换目标文件"""
|
||
tmp_target = str(dst) + ".tmp"
|
||
src.replace(tmp_target)
|
||
if dst.exists():
|
||
os.unlink(str(dst))
|
||
os.rename(tmp_target, str(dst))
|
||
|
||
|
||
def _download_from_mirror() -> bool:
|
||
"""从 GitHub 社区镜像下载(无需 License Key,直接下载 .mmdb)
|
||
使用 GitHub API 获取 raw download_url,比直接访问 raw.githubusercontent.com 更稳
|
||
"""
|
||
import base64
|
||
import requests
|
||
|
||
api_url = f"https://api.github.com/repos/{MIRROR_REPO}/contents/{MIRROR_FILE}?ref={MIRROR_BRANCH}"
|
||
print(f"[GeoLite2] 尝试镜像: {MIRROR_REPO}/{MIRROR_BRANCH}/{MIRROR_FILE}")
|
||
try:
|
||
resp = requests.get(api_url, timeout=30, headers={"Accept": "application/vnd.github.v3+json"})
|
||
if resp.status_code != 200:
|
||
print(f"[GeoLite2] GitHub API 返回 {resp.status_code}: {resp.text[:200]}")
|
||
return False
|
||
info = resp.json()
|
||
size = info.get("size", 0)
|
||
download_url = info.get("download_url")
|
||
encoding = info.get("encoding", "")
|
||
content_b64 = info.get("content", "")
|
||
|
||
if not download_url and not content_b64:
|
||
print(f"[GeoLite2] GitHub API 未返回下载链接或内容")
|
||
return False
|
||
|
||
print(f"[GeoLite2] 镜像文件大小: {size / (1024*1024):.1f} MB")
|
||
|
||
# 方式1: 直接从 download_url 下载(raw.githubusercontent.com,国内可能超时)
|
||
if download_url:
|
||
print(f"[GeoLite2] 尝试 raw 直链...")
|
||
try:
|
||
raw_resp = requests.get(download_url, timeout=120, stream=True,
|
||
headers={"User-Agent": "geoip-downloader/1.0"})
|
||
if raw_resp.status_code == 200:
|
||
return _save_raw_stream(raw_resp)
|
||
print(f"[GeoLite2] raw 直链返回 {raw_resp.status_code}")
|
||
except Exception as e:
|
||
print(f"[GeoLite2] raw 直链失败: {e}")
|
||
|
||
# 方式2: 从 API 返回的 base64 content 解码(GitHub API 对 >1MB 文件不返回 content)
|
||
if content_b64 and encoding == "base64":
|
||
print(f"[GeoLite2] 尝试 API base64 内容...")
|
||
try:
|
||
raw = base64.b64decode(content_b64)
|
||
tmp_target = str(DB_PATH) + ".tmp"
|
||
with open(tmp_target, "wb") as f:
|
||
f.write(raw)
|
||
_atomic_replace(Path(tmp_target), DB_PATH)
|
||
_write_stamp()
|
||
size_mb = DB_PATH.stat().st_size / (1024 * 1024)
|
||
print(f"[GeoLite2] 镜像下载完成: {DB_PATH} ({size_mb:.1f} MB)")
|
||
return True
|
||
except Exception as e:
|
||
print(f"[GeoLite2] base64 解码失败: {e}")
|
||
|
||
except Exception as e:
|
||
print(f"[GeoLite2] 镜像下载失败: {e}")
|
||
|
||
return False
|
||
|
||
|
||
def _save_raw_stream(resp) -> bool:
|
||
"""保存流式响应到文件"""
|
||
tmp_target = str(DB_PATH) + ".tmp"
|
||
try:
|
||
with open(tmp_target, "wb") as f:
|
||
for chunk in resp.iter_content(chunk_size=65536):
|
||
f.write(chunk)
|
||
# 校验大小(GeoLite2-City 至少 30MB)
|
||
size = Path(tmp_target).stat().st_size
|
||
if size < 30_000_000:
|
||
print(f"[GeoLite2] 下载文件过小 ({size} bytes),可能损坏,已丢弃")
|
||
os.unlink(tmp_target)
|
||
return False
|
||
_atomic_replace(Path(tmp_target), DB_PATH)
|
||
_write_stamp()
|
||
size_mb = DB_PATH.stat().st_size / (1024 * 1024)
|
||
print(f"[GeoLite2] 镜像下载完成: {DB_PATH} ({size_mb:.1f} MB)")
|
||
return True
|
||
except Exception as e:
|
||
print(f"[GeoLite2] 保存失败: {e}")
|
||
if Path(tmp_target).exists():
|
||
os.unlink(tmp_target)
|
||
return False
|
||
|
||
|
||
def _write_stamp():
|
||
"""记录更新时间戳"""
|
||
STAMP_PATH.write_text(str(int(time.time())), encoding="utf-8")
|
||
|
||
|
||
def _needs_update() -> bool:
|
||
"""判断是否需要更新(不存在或超过 7 天)"""
|
||
if not DB_PATH.exists():
|
||
return True
|
||
if not STAMP_PATH.exists():
|
||
return True
|
||
try:
|
||
last = int(STAMP_PATH.read_text(encoding="utf-8").strip())
|
||
age_days = (time.time() - last) / 86400
|
||
return age_days >= UPDATE_INTERVAL_DAYS
|
||
except Exception:
|
||
return True
|
||
|
||
|
||
def download(license_key: str = "", account_id: str = "", force: bool = False) -> bool:
|
||
"""
|
||
下载/更新 GeoLite2-City 数据库
|
||
|
||
Args:
|
||
license_key: MaxMind License Key(为空则尝试镜像)
|
||
account_id: MaxMind Account ID(新版 API 需要,登录后在账号概览页可见)
|
||
force: 是否强制重新下载
|
||
|
||
Returns:
|
||
bool: 是否成功
|
||
"""
|
||
if not force and DB_PATH.exists() and not _needs_update():
|
||
size_mb = DB_PATH.stat().st_size / (1024 * 1024)
|
||
print(f"[GeoLite2] 数据库已是最新,跳过下载 ({size_mb:.1f} MB)")
|
||
return True
|
||
|
||
# 优先用 License Key 下载
|
||
if license_key:
|
||
if _download_with_license_key(license_key, account_id):
|
||
return True
|
||
print("[GeoLite2] 官方下载失败,尝试镜像...")
|
||
|
||
# 降级到镜像
|
||
if _download_from_mirror():
|
||
return True
|
||
|
||
print("[GeoLite2] 所有下载方式均失败")
|
||
print(" → 请注册 MaxMind 免费账号获取 License Key:")
|
||
print(" https://www.maxmind.com/en/geolite2/signup")
|
||
print(" → 然后运行: python app/download_geolite2.py --account-id YOUR_ID --license-key YOUR_KEY")
|
||
return False
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description="GeoLite2-City 数据库下载工具")
|
||
parser.add_argument("--account-id", default=os.environ.get("MAXMIND_ACCOUNT_ID", ""),
|
||
help="MaxMind Account ID(新版 API 需要,也可通过 MAXMIND_ACCOUNT_ID 环境变量配置)")
|
||
parser.add_argument("--license-key", default=os.environ.get("MAXMIND_LICENSE_KEY", ""),
|
||
help="MaxMind License Key(也可通过 MAXMIND_LICENSE_KEY 环境变量配置)")
|
||
parser.add_argument("--force", action="store_true", help="强制重新下载")
|
||
args = parser.parse_args()
|
||
|
||
success = download(license_key=args.license_key, account_id=args.account_id, force=args.force)
|
||
sys.exit(0 if success else 1)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|