【问题标题】:Python: Pass a list of IP addresses to geoip2 for location lookupPython:将 IP 地址列表传递给 geoip2 以进行位置查找
【发布时间】:2023-03-11 17:23:01
【问题描述】:

我正在寻找一种方法来分析包含位置数据的大量 IP 地址列表。这个列表大约有 10000000 个条目。

目前我正在使用 maxmind 的 geoip2 模块。原始代码可以查找单个IP地址条目并打印带有国家代码的结果,如下所示:

import geoip2.database
reader = geoip2.database.Reader('./GeoLite2-Country_20210330/GeoLite2-Country.mmdb')
response = reader.country('80.80.80.80')
print('response.country.iso_code: {}'.format(response.country.iso_code))
reader.close()

我试图找出一种扩展此脚本的方法,以便通过遍历 csv 文件一次搜索更多条目。我写了一个不能按我想工作的代码。似乎 Python 不喜欢我传递列表的方式。

import geoip2.database
from csv import reader
import csv

read_db = geoip2.database.Reader('./GeoLite2-Country_20210330/GeoLite2-Country.mmdb')
with open('SrcIP.csv', 'r') as file1:
csv_read = csv.reader(file1, delimiter=' ', quotechar='|')
    for row in csv_read:
        response = read_db.country(', '.join(row))
        print(response) #note 1
        print('response.country: {}'.format(read_db.country)) #note 2

注意 1:如果我直接打印响应变量,它会在数据库中搜索 IP 地址范围并打印每个 IP 地址的所有可用信息。结果,每一行的输出都变得太多了。

注意 2:此行将输出限制为仅国家代码。但是,它会为每一行返回错误,如下所示:

response.country: >

【问题讨论】:

    标签: python-3.x geolocation ip-address lookup geoip2


    【解决方案1】:

    我想我已经设法解决了我自己的问题。 我将代码更改为:

    import geoip2.database
    import csv
    
    read_db = geoip2.database.Reader('./GeoLite2-Country_20210330/GeoLite2-Country.mmdb') #read database
    with open('SrcIP.csv', 'r') as file1:
         csv_read = csv.reader(file1, delimiter=' ', quotechar='|')
         for row in csv_read:
             response = read_db.country(', '.join(row))
             filtered_res = response.country.iso_code
             print(filtered_res)
    

    让我知道你的想法。我用给定的 IP 地址交叉检查了结果,国家代码似乎是正确的。

    【讨论】:

      猜你喜欢
      • 2013-11-15
      • 2018-04-05
      • 1970-01-01
      • 2013-12-17
      • 2018-01-05
      • 1970-01-01
      • 2019-03-22
      • 2016-04-03
      • 1970-01-01
      相关资源
      最近更新 更多