You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于域名查询所属国家并按国家码分类存储至对应文本文件

解决方案:修改脚本实现按国家码存储域名信息

看起来你需要把域名对应的归属国信息按国家码分类存入对应文本文件,原脚本目前只是打印输出,我们可以调整它来实现文件写入功能,同时处理一些常见异常情况(比如域名解析失败、无法获取国家信息)。

修改后的完整脚本

#!/usr/bin/python
import socket
from geolite2 import geolite2

def save_to_country_file(domain_str, ip, country_code):
    # 处理国家码为空的情况,统一存入unknown.txt
    filename = f"{country_code.upper()}.txt" if country_code else "unknown.txt"
    # 用追加模式打开文件,避免覆盖已有内容
    with open(filename, 'a', encoding='utf-8') as f:
        # 写入格式化的信息,你可以根据需求调整输出格式
        f.write(f"{domain_str.strip()} [{ip}]: {country_code or 'Unknown'}\n")
    print(f"已写入 {filename}: {domain_str.strip()} [{ip}]: {country_code or 'Unknown'}")

def get_country_from_ip(ip):
    reader = geolite2.reader()
    try:
        data = reader.get(ip)
        # 校验GeoLite2返回的数据结构,确保能拿到国家码
        if data and 'country' in data and 'iso_code' in data['country']:
            return data['country']['iso_code']
        return None
    finally:
        # 确保关闭reader,避免资源泄漏
        reader.close()

def process_domain(domain_str):
    try:
        ip = socket.gethostbyname(domain_str.strip())
        country_code = get_country_from_ip(ip)
        save_to_country_file(domain_str, ip, country_code)
    except socket.gaierror:
        print(f"无法解析域名: {domain_str.strip()}")
        # 把解析失败的域名单独存入failed.txt
        with open("failed.txt", 'a', encoding='utf-8') as f:
            f.write(f"解析失败: {domain_str.strip()}\n")

# 示例:处理域名列表
if __name__ == "__main__":
    # 你可以替换成自己的域名列表,或者从文件读取域名
    domains = ["google.com", "example.fr", "invalid-domain-test.com"]
    for domain in domains:
        process_domain(domain)

关键修改点说明

  • 拆分功能模块:把原有的逻辑拆分成三个独立函数,让代码更清晰易维护:
    • get_country_from_ip:专门负责从IP地址获取国家码
    • save_to_country_file:处理文件写入逻辑
    • process_domain:统筹单个域名的解析、查国家、写入全流程
  • 文件写入优化:使用with open上下文管理器自动管理文件资源,采用追加模式('a')确保同一个国家的域名信息会累加在对应文件中
  • 异常处理:捕获域名解析失败的socket.gaierror异常,将失败域名存入failed.txt;同时处理GeoLite2无法获取国家信息的情况,存入unknown.txt
  • 资源管理:在get_country_from_ip中用finally块确保GeoLite2的reader被正确关闭,避免资源泄漏

使用说明

  1. 先确保安装了依赖库:
pip install maxminddb-geolite2
  1. 如果你有批量域名需要处理,可以从文本文件读取域名(比如domains.txt),替换示例中的domains列表:
# 从文件读取域名的示例
with open("domains.txt", 'r', encoding='utf-8') as f:
    domains = [line.strip() for line in f if line.strip()]
for domain in domains:
    process_domain(domain)

运行脚本后,就会自动生成对应国家码的文本文件,每个文件里会记录该国家的域名、IP和归属国信息啦。

内容的提问来源于stack exchange,提问作者X-HAT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:42:01