python操作常见ip库
代码:
# -*- coding:utf-8 _*_ #https://github.com/adysec/IP_database ips = ['221.217.124.31', '39.124.24.160', '61.149.13.174', '61.149.15.18', '121.17.130.96'] print('qqwry.dat库:') #pip install qqwry-py3 from qqwry import QQwry q = QQwry() q.load_file('qqwry.dat') for ip in ips: result = q.lookup(ip) print(','.join(result)) print() print('IP2Region库:') from ipregion import IP2Region ip2region = IP2Region() for ip in ips: region = ip2region.search(ip) print(region) print() print('ip2region.xdb库:') #https://github.com/lionsoul2014/ip2region/tree/master/binding/python from xdbSearcher import XdbSearcher searcher = XdbSearcher(dbfile='ip2region.xdb') for ip in ips: region_str = searcher.searchByIPStr(ip) print(region_str) searcher.close() print() print('IPDB库:') #https://github.com/ipipdotnet/ipdb-python/tree/master import ipdb db = ipdb.City("city.free.ipdb") for ip in ips: print(db.find_map(ip, "CN")) print() print('GeoLite.mmdb:') db_path = 'GeoLite2-City.mmdb' import geoip2.database with geoip2.database.Reader(db_path, locales=['zh-CN']) as reader: for ip in ips: response = reader.city(ip) location_info = { 'country': response.country.name, # 国家名称,中文显示 'province': response.subdivisions.most_specific.name, # 省份名称,中文显示 'city': response.city.name, # 城市名称,中文显示 } print(location_info) print()
执行结果:
qqwry.dat库: 中国–北京–北京–通州区,联通 韩国,CZ88.NET 中国–北京–北京–朝阳区,联通 中国–北京–北京–朝阳区,联通 中国–河北–衡水,联通 IP2Region库: {'errno': 0, 'data': {'region': '中国北京', 'ip': '221.217.124.31'}, 'source': 'Cache From searchWithIpWhoIs at 2025-08-05 16:22:51'} {'errno': 0, 'data': {'region': '中国北京', 'ip': '221.217.124.31'}, 'source': 'Cache From searchWithIpWhoIs at 2025-08-05 16:22:51'} {'errno': 0, 'data': {'region': '中国北京', 'ip': '221.217.124.31'}, 'source': 'Cache From searchWithIpWhoIs at 2025-08-05 16:22:51'} {'errno': 0, 'data': {'region': '中国北京', 'ip': '221.217.124.31'}, 'source': 'Cache From searchWithIpWhoIs at 2025-08-05 16:22:51'} {'errno': 0, 'data': {'region': '中国北京', 'ip': '221.217.124.31'}, 'source': 'Cache From searchWithIpWhoIs at 2025-08-05 16:22:51'} ip2region.xdb库: 中国|0|北京|北京市|联通 韩国|0|0|0|SK宽带 中国|0|北京|北京市|联通 中国|0|北京|北京市|联通 中国|0|河北省|衡水市|联通 IPDB库: {'country_name': '中国', 'region_name': '北京', 'city_name': '北京'} {'country_name': '韩国', 'region_name': '韩国', 'city_name': ''} {'country_name': '中国', 'region_name': '北京', 'city_name': '北京'} {'country_name': '中国', 'region_name': '北京', 'city_name': '北京'} {'country_name': '中国', 'region_name': '河北', 'city_name': '衡水'} GeoLite.mmdb: {'country': '中国', 'province': '北京市', 'city': '北京'} {'country': '韩国', 'province': '京畿道', 'city': None} {'country': '中国', 'province': '北京市', 'city': '北京'} {'country': '中国', 'province': '北京市', 'city': '北京'} {'country': '中国', 'province': None, 'city': None}
本文来自博客园,作者:河北大学-徐小波,转载请注明原文链接:https://www.cnblogs.com/xuxiaobo/p/19023640

浙公网安备 33010602011771号