如何优化检查IP地址和获取国家?

问题描述

在 Win10 上使用 Python 3.9.2 我试图在日志文件(大约 65000 行)中获取 IP 地址的国家/地区。我有一个包含 IP 范围(22000 行)和相应国家/地区的 .csv,如下所示:

[...]
2.16.9.0,2.16.9.255,DE,Germany
2.16.11.0,2.16.11.255,FR,France
2.16.12.0,2.16.13.255,CH,Switzerland
2.16.23.0,2.16.23.255,Germany
2.16.30.0,2.16.33.255,Germany
2.16.34.0,2.16.34.255,France
[...]

我正在使用 python 的 ipaddress 并遍历范围列表并检查当前 IP 是否在获取国家/地区的范围内。之前,我会检查两个条件是否为真。

我的目标是计算来自三个国家/地区中每个国家/地区的连接数。一个例子:

import ipaddress
import csv

with open (PATH) as logfile
    logfile_lines = [line.split('\t') for line in logfile]

with open (PATH,r) as ipdaten
    ipdaten_lines = [line.split(',') for line in ipdaten]

streams_france=0

for line in logfile_lines:
    line2 = int(line[9])
    stream = str(line[3])
    iplog = line[1]
    ipobj= ipaddress.ip_address(iplog)

    [...]
    if line2 > 60 and stream == "stream2":
         for ips in ipdaten_lines:

            if ipobj >= ipaddress.IPv4Address(ips[0]) and ipobj <= ipaddress.IPv4Address(ips[1]):
                land = ips[3]

                if land == "France\n":
                    streams_france+=1
                break

     [...]

代码有效,但速度很慢。 1个多小时后,它仍在运行。对于 line2 > 60 and stream == "stream2",大约有 9000 种情况都是 True

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)