Python通过Geoip解析IP地址信息

最近在研究ELK日志分析系统,在分析haproxy日志时,考虑需要将haproxy内获取到的IP地址进行解析,于是有了这么一个需求。奈何maxmind数据库有些不准确,于是衍生出了一个想法, 要测试maxmind数据库的准确性。于是乎想到了一个简单的方法,利用python脚本来配置geoip数据库来解析地址,来筛选较为正确的地址库用于elk系统。

准备条件

  • 一台Linux系统,系统内安装有python3
  • python3有安装如下插件
apt install -y python3-pip
pip3 install Flask
pip3 install geoip2

注册账号后就可以免费下载

代码准备

from flask import Flask, request
from geoip2 import database
import re

app = Flask(__name__)

# 假设 GeoLite2-City.mmdb 文件位于 /root/ge01/ 目录下
reader = database.Reader('/root/ge01/GeoLite2-City.mmdb')

# 定义内网地址的正则表达式
INTERNAL_IP_PATTERN = r'^(127\.|10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.)'

@app.route('/')
def index():
    return 'Welcome to the IP Address Recognition Website!'

@app.route('/<ip>')
def get_ip_info(ip):
    # 检查 IP 是否为内网地址
    if re.match(INTERNAL_IP_PATTERN, ip):
        return '局域网地址'
    else:
        try:
            response = reader.city(ip)
            country = response.country.name
            subdivisions =  response.subdivisions.most_specific.name
            city = response.city.name
            latitude = response.location.latitude
            longitude = response.location.longitude
            return f"网络地址: {ip}<br>国家: {country}<br>省份: {subdivisions}<br>城市: {city}<br>纬度: {latitude}<br>经度: {longitude}"
        except Exception as e:
            return f"Error: {str(e)}"

if __name__ == '__main__':
    # 注意:在生产环境中,不建议将 Flask 应用直接运行在 host='0.0.0.0' 和 port=80 上
    # 因为这可能需要额外的配置和安全考虑。这里仅为示例。
    app.run(host='0.0.0.0', port=80)

代码运行

root@MaxMind:~# python3 ip.py 
 * Serving Flask app 'ip'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:80
 * Running on http://192.168.1.10:80
Press CTRL+C to quit

查询IP地址信息

本次测试拿的是阿里DNS公网地址进行测试,可以完美的显示出地址的详细信息,唯一的缺点就是这个现实为英文

  • 解析公网地址情况
  • 解析国外地址情况
  • 解析内网IP情况
posted @ 2024-05-17 11:20  二乘八是十六  阅读(167)  评论(0编辑  收藏  举报