Python如何通过ip2region解析IP获得地域信息

作者:亿万行代码的梦 时间:2021-08-02 12:59:04 

通过ip2region解析IP获得地域信息

目标,从给的读取给的ip地址文件解析出ip地域名并输出CSV文件,我选用的是开源ip2region。ip2region地址

下载好后直接用pycharm打开,因为我用的是python所以其他语言我就忽略了。

这里我对代码进行了编辑从而实现自己的目的。


Python如何通过ip2region解析IP获得地域信息

主要对benchmark.py进行了修改。

代码如下:

import threading
import time, sys

from ip2Region import Ip2Region

class BenchmarkThread(threading.Thread):
   __searcher = None
   __lock = None

def __init__(self, searcher, lock):
       self.__searcher = searcher
       self.__lock = lock
       threading.Thread.__init__(self)

def run(self):
   #输入路径,每行为一个IP地址
       for IP in open("D:\****\****.txt"):
           self.__lock.acquire()
           try:
               data = self.__searcher.memorySearch(IP)
               region=str(data["region"].decode('utf-8'))
               #print(region.split("|"))
               city=""
               province=""
               regions=region.split("|")
               if(regions[3]=="0"):
                   city=""
               else:
                   city=regions[3]

if (regions[2] == "0"):
                   province = ""
               else:
                   province = regions[2]
print(IP.strip()+","+regions[0]+province+city+regions[4])
               result=IP.strip()+","+regions[0]+province+city+" "+regions[4]
               with open('*****.csv', 'a') as f:  # 设置文件对象
                   f.write(result+"\n")

finally:
               self.__lock.release()

if __name__ == "__main__":
   dbFile = "D:\pythonProject\hx_hdfs_local\ip2region-master\data\ip2region.db"
   if ( len(sys.argv) > 2 ):
       dbFile = sys.argv[1];

threads = []
   searcher = Ip2Region(dbFile)
   lock = threading.Lock()

for i in range(1):
       t = BenchmarkThread(searcher, lock)
       threads.append(t)

sTime = time.time() * 1
   for t in threads:
       t.start()

for t in threads:
       t.join()
   eTime = time.time() * 1

#print("Benchmark done: %5f" % (eTime - sTime))

结果对比:


Python如何通过ip2region解析IP获得地域信息


Python如何通过ip2region解析IP获得地域信息

ip2region的使用总结

ip2region 简介

根据它获取一个具体ip的信息,通过IP解析出国家、具体地址、网络服务商等相关信息。

ip2region 实际应用

在开发中,我们需要记录登陆的日志信息,关于登陆者的ip和位置信息,可以通过ip2region来实现。

Spring Boot集成ip2region

第一步:pom.xml引入

    <properties>
        <ip2region.version>1.7.2</ip2region.version>
    </properties>
 
   <dependency>
        <groupId>org.lionsoul</groupId>
        <artifactId>ip2region</artifactId>
        <version>${ip2region.version}</version>
    </dependency>

第二步:下载ip2region.db

$ git clone https://gitee.com/lionsoul/ip2region.git

下载这个项目之后到data/文件夹下面找到ip2region.db复制到项目resources下

下载这个项目之后到data/文件夹下面找到ip2region.db复制到项目resources下

Python如何通过ip2region解析IP获得地域信息

第三步:ip2region 工具类

功能:主要基于IP获取当前位置信息。

import org.apache.commons.io.IOUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

/**
* @author zhouzhiwengang
*/
public class AddressUtil {

private static Logger log = LoggerFactory.getLogger(AddressUtil.class);

@SuppressWarnings("all")
   public static String getCityInfo(String ip) {
       //db
       String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.db").getPath();
       File file = new File(dbPath);

if (!file.exists()) {
           log.info("地址库文件不存在,进行其他处理");
           String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
           dbPath = tmpDir + File.separator + "ip2region.db";
           log.info("临时文件路径:{}", dbPath);
           file = new File(dbPath);
           if (!file.exists() || (System.currentTimeMillis() - file.lastModified() > 86400000L)) {
               log.info("文件不存在或者文件存在时间超过1天进入...");
               try {
                   InputStream inputStream = new ClassPathResource("ip2region/ip2region.db").getInputStream();
                   IOUtils.copy(inputStream, new FileOutputStream(file));
               } catch (IOException exception) {
                   exception.printStackTrace();
               }
           }
       }

//查询算法
       int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
       try {
           DbConfig config = new DbConfig();
           DbSearcher searcher = new DbSearcher(config, dbPath);
           //define the method
           Method method = null;
           switch (algorithm) {
               case DbSearcher.BTREE_ALGORITHM:
                   method = searcher.getClass().getMethod("btreeSearch", String.class);
                   break;
               case DbSearcher.BINARY_ALGORITHM:
                   method = searcher.getClass().getMethod("binarySearch", String.class);
                   break;
               case DbSearcher.MEMORY_ALGORITYM:
                   method = searcher.getClass().getMethod("memorySearch", String.class);
                   break;
           }
           DataBlock dataBlock = null;
           if (Util.isIpAddress(ip) == false) {
               log.error("Error: Invalid ip address");
           }
           dataBlock = (DataBlock) method.invoke(searcher, ip);
           return dataBlock.getRegion();
       } catch (Exception e) {
           e.printStackTrace();
       }
       return null;
   }
}

知识拓展

遇到的问题:由于AddressUtil.java 工具类是处于项目common(基础通用模块),但部署到tomcat 容器中,提示无法加载ip2region.db 数据库资源文件。

产生上述问题的原因是:项目common(基础通用模块)没有把resources 资源文件夹下的相关资源打包,仅需要将ip2region.db 打包之项目common(基础通用模块).jar 中即可。

解决办法:改造项目common(基础通用模块)的pom.xml 文件,添加如下代码片段:

<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**.*</include>
<include>**/*.*</include><!-- i18n能读取到 -->
<include>**/*/*.*</include>
</includes>
</resource>
</resources>
</build>

来源:https://blog.csdn.net/qq_41744529/article/details/124321760

标签:Python,ip2region,IP,地域信息
0
投稿

猜你喜欢

  • 符合标准的纯CSS三 级弹出菜单

    2008-01-06 15:34:00
  • PyCharm常用配置和常用插件(小结)

    2023-07-21 03:21:17
  • 10个python3常用排序算法详细说明与实例(快速排序,冒泡排序,桶排序,基数排序,堆排序,希尔排序,归并排序,计数排序)

    2021-05-21 05:28:13
  • 如何用Python对数学函数进行求值、求偏导

    2023-10-13 04:58:01
  • django 连接数据库 sqlite的例子

    2023-08-03 19:03:15
  • js求一组数中的最大数

    2008-04-10 12:00:00
  • SQL Server和MySql中创建临时表

    2008-06-19 13:31:00
  • Cookies 欺骗漏洞的防范方法(vbs+js 实现)

    2011-03-09 11:09:00
  • sql 存储过程分页代码 支持亿万庞大数据量

    2011-09-30 11:16:46
  • access MDB 转换为 Execl(ASP类)

    2008-07-19 12:10:00
  • Python-copy()与deepcopy()区别详解

    2021-06-20 15:00:41
  • asp如何生成XML数据

    2007-08-20 09:50:00
  • Python使用LRU缓存策略进行缓存的方法步骤

    2023-09-03 05:00:06
  • django admin后管定制-显示字段的实例

    2023-07-01 11:34:18
  • 从绘画语言的发展,看视觉设计风格

    2008-08-03 17:11:00
  • asp最简单的生成验证码代码

    2011-03-07 11:05:00
  • golang定时器和超时的使用详解

    2023-07-23 21:35:12
  • Python 文件处理之open()函数

    2021-03-04 02:26:49
  • python的keyword模块用法实例分析

    2022-04-06 07:56:22
  • Python测试开源工具splinter安装与使用教程

    2022-07-22 01:56:36
  • asp之家 网络编程 m.aspxhome.com