Python如何通過(guò)ip2region解析IP獲得地域信息
通過(guò)ip2region解析IP獲得地域信息
目標(biāo),從給的讀取給的ip地址文件解析出ip地域名并輸出CSV文件,我選用的是開(kāi)源ip2region。ip2region地址
下載好后直接用pycharm打開(kāi),因?yàn)槲矣玫氖莗ython所以其他語(yǔ)言我就忽略了。
這里我對(duì)代碼進(jìn)行了編輯從而實(shí)現(xiàn)自己的目的。

主要對(duì)benchmark.py進(jìn)行了修改。
代碼如下:
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):
#輸入路徑,每行為一個(gè)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: # 設(shè)置文件對(duì)象
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))結(jié)果對(duì)比:


ip2region的使用總結(jié)
ip2region 簡(jiǎn)介
根據(jù)它獲取一個(gè)具體ip的信息,通過(guò)IP解析出國(guó)家、具體地址、網(wǎng)絡(luò)服務(wù)商等相關(guān)信息。
ip2region 實(shí)際應(yīng)用
在開(kāi)發(fā)中,我們需要記錄登陸的日志信息,關(guān)于登陸者的ip和位置信息,可以通過(guò)ip2region來(lái)實(shí)現(xiàn)。
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
下載這個(gè)項(xiàng)目之后到data/文件夾下面找到ip2region.db復(fù)制到項(xiàng)目resources下
下載這個(gè)項(xiàng)目之后到data/文件夾下面找到ip2region.db復(fù)制到項(xiàng)目resources下

第三步:ip2region 工具類(lèi)
功能:主要基于IP獲取當(dāng)前位置信息。
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("地址庫(kù)文件不存在,進(jìn)行其他處理");
String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
dbPath = tmpDir + File.separator + "ip2region.db";
log.info("臨時(shí)文件路徑:{}", dbPath);
file = new File(dbPath);
if (!file.exists() || (System.currentTimeMillis() - file.lastModified() > 86400000L)) {
log.info("文件不存在或者文件存在時(shí)間超過(guò)1天進(jìn)入...");
try {
InputStream inputStream = new ClassPathResource("ip2region/ip2region.db").getInputStream();
IOUtils.copy(inputStream, new FileOutputStream(file));
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
//查詢(xún)算法
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;
}
}知識(shí)拓展
遇到的問(wèn)題:由于AddressUtil.java 工具類(lèi)是處于項(xiàng)目common(基礎(chǔ)通用模塊),但部署到tomcat 容器中,提示無(wú)法加載ip2region.db 數(shù)據(jù)庫(kù)資源文件。
產(chǎn)生上述問(wèn)題的原因是:項(xiàng)目common(基礎(chǔ)通用模塊)沒(méi)有把resources 資源文件夾下的相關(guān)資源打包,僅需要將ip2region.db 打包之項(xiàng)目common(基礎(chǔ)通用模塊).jar 中即可。
解決辦法:改造項(xiàng)目common(基礎(chǔ)通用模塊)的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>
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Pytorch中如何調(diào)用forward()函數(shù)
這篇文章主要介紹了Pytorch中如何調(diào)用forward()函數(shù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
Linux 下 Python 實(shí)現(xiàn)按任意鍵退出的實(shí)現(xiàn)方法
這篇文章主要介紹了Linux 下 Python 實(shí)現(xiàn)按任意鍵退出的實(shí)現(xiàn)方法的相關(guān)資料,本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09
Python 實(shí)現(xiàn)給圖片加文字或logo水印
本文主要為大家介紹了給圖片添加文字或者logo圖片水印的python工具,從而打造你的專(zhuān)屬圖片。代碼簡(jiǎn)潔易懂,感興趣的小伙伴可以了解一下2021-11-11
PyTorch CNN實(shí)戰(zhàn)之MNIST手寫(xiě)數(shù)字識(shí)別示例
本篇文章主要介紹了PyTorch CNN實(shí)戰(zhàn)之MNIST手寫(xiě)數(shù)字識(shí)別示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
python關(guān)閉windows進(jìn)程的方法
這篇文章主要介紹了python關(guān)閉windows進(jìn)程的方法,涉及Python調(diào)用系統(tǒng)命令操作windows進(jìn)程的技巧,需要的朋友可以參考下2015-04-04
用Python實(shí)現(xiàn)寫(xiě)倒序輸出(任意位數(shù))
這篇文章主要介紹了用Python實(shí)現(xiàn)寫(xiě)倒序輸出(任意位數(shù)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
Python如何實(shí)現(xiàn)機(jī)器人聊天
這篇文章主要介紹了Python如何實(shí)現(xiàn)機(jī)器人聊天,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-09-09

