python使用ip2Region库查询ip地址归属地查询/ip朔源自动生成Excel报告

背景:

方式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 xlwtdef testSearch(ip_s):dbFile = "../../data/ip2region.db"searcher = Ip2Region(dbFile)try:print("开始检测:",(ip_s))sTime = time.time() * 1000data = searcher.binarySearch(ip_s)# elif algorithm == "memory":#     data = searcher.memorySearch(line)# else:#     data = searcher.btreeSearch(line)eTime = time.time() * 1000ip_info = ("%s|%s|%s" % (ip_s, data["city_id"], data["region"].decode('utf-8')))print("检测完成:" + ip_info)return ip_infoexcept Exception as e:print("[Error]: %s" % e)searcher.close()def all_in():row_id = 1book = 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 += 1else: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 += 1else: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 += 1else: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 += 1else: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 += 1except Exception as e:print("[Error]: %s" % e)sheet.write(row_id, 0, ip)sheet.write(row_id, 1, "检测异常,请手动检测!")row_id += 1book.save('score.xls')if __name__ == "__main__":all_in()

备注:
1、需要将ip地址整理到脚本同级目录,ip.txt文件。
2、地址库需要从Git下载,下载地址:
https://blog.csdn.net/weixin_34247032/article/details/92863280


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部