背景:
方式1:调用外部接口
比如:
http://freeapi.ipip.net/ip
缺点:该接口会对同一个IP下面的请求做限制,导致部分IP无法查询;切时刻需要依赖外网,所以推荐使用方式2实现;
方式2:使用本地ip2Region地址库实现
优点:速度快,不依赖外网,地址全,有运营商信息
主体源码如下(自动生成Excel报告):
#-*- coding:utf-8 -*-
import struct, sys, os, time
from platform import python_version
from ip2Region import Ip2Region
import xlwt
def testSearch(ip_s):
dbFile = "../../data/ip2region.db"
searcher = Ip2Region(dbFile)
try:
print("开始检测:",(ip_s))
sTime = time.time() * 1000
data = searcher.binarySearch(ip_s)
# elif algorithm == "memory":
# data = searcher.memorySearch(line)
# else:
# data = searcher.btreeSearch(line)
eTime = time.time() * 1000
ip_info = ("%s|%s|%s" % (ip_s, data["city_id"], data["region"].decode('utf-8')))
print("检测完成:" + ip_info)
return ip_info
except Exception as e:
print("[Error]: %s" % e)
searcher.close()
def all_in():
row_id = 1
book = xlwt.Workbook()
sheet = book.add_sheet('sheet')
title = ['源ip', '国家', '省市','运营商']
for col in range(len(title)):
sheet.write(0, col, title[col])
with open('ip.txt' ,'r') as file:
for line in file.readlines():
ip = line.strip()
try:
data = testSearch(ip)
ct = data.split('|')[2].strip()
pv = data.split('|')[4].strip()
city = data.split('|')[5].strip()
yys = data.split('|')[6].strip()
if ct == "0":
print("地址库中未找到对应的IP归属地,请更新地址库或者确定ip准确性!")
sheet.write(row_id, 0, ip)
sheet.write(row_id, 1, "/")
sheet.write(row_id, 2, "/")
sheet.write(row_id, 3, "/")
row_id += 1
else:
if pv == "0":
print("省市查询为空!")
sheet.write(row_id, 0, ip)
sheet.write(row_id, 1, ct)
sheet.write(row_id, 2, "/")
sheet.write(row_id, 3, "/")
row_id += 1
else:
if city == "0":
sheet.write(row_id, 0, ip)
sheet.write(row_id, 1, ct)
sheet.write(row_id, 2, pv + "-" + "///")
sheet.write(row_id, 3, "/")
row_id += 1
else:
if yys == "0":
sheet.write(row_id, 0, ip)
sheet.write(row_id, 1, ct)
sheet.write(row_id, 2, pv + "-" + city)
sheet.write(row_id, 3, "/")
row_id += 1
else:
sheet.write(row_id, 0, ip)
sheet.write(row_id, 1, ct)
sheet.write(row_id, 2, pv + "-" + city)
sheet.write(row_id, 3, yys)
row_id += 1
except Exception as e:
print("[Error]: %s" % e)
sheet.write(row_id, 0, ip)
sheet.write(row_id, 1, "检测异常,请手动检测!")
row_id += 1
book.save('score.xls')
if __name__ == "__main__":
all_in()
备注:
1、需要将ip地址整理到脚本同级目录,ip.txt文件。
2、地址库需要从Git下载,下载地址:
https://blog.youkuaiyun.com/weixin_34247032/article/details/92863280