You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
3.3 KiB
Python

7 months ago
import json
from progress.bar import Bar
# 删除data/ip.merge.txt文件
try:
with open('data/ip.merge.txt', 'w', encoding='utf-8') as f:
f.write('')
print('data/ip.merge.txt文件已清空')
except Exception as e:
print(f"不存在该文件")
# 读取数据文件
with open('data/location/countries.json', 'r', encoding='utf-8') as f:
countries_data = json.load(f)['RECORDS']
with open('data/location/states.json', 'r', encoding='utf-8') as f:
states_data = json.load(f)['RECORDS']
with open('data/location/cities.json', 'r', encoding='utf-8') as f:
cities_data = json.load(f)['RECORDS']
with open('data/network/lsp_idc.json', 'r', encoding='utf-8') as f:
lsp_idc_data = json.load(f)['RECORDS']
with open('data/network/lsp.json', 'r', encoding='utf-8') as f:
lsp_data = json.load(f)['RECORDS']
# 使用cn_data.json进行省份匹配
with open('data/location/cn_data.json', 'r', encoding='utf-8') as f:
cn_data = json.load(f)
# 读取ip.txt文件
with open('data/ip.txt', 'r', encoding='utf-8') as f:
ip_data = f.readlines()
# 匹配国家、省份、城市和运营商
bar = Bar('Processing', max=len(ip_data))
try:
with open('data/ip.merge.txt', 'w', encoding='utf-8') as output_file:
for line in ip_data:
line_data = line.split()
ip_range = line_data[0], line_data[1]
country_name = line_data[2]
# 对中国进行反向匹配
if any(province in country_name for province in ['河北', '山西', '辽宁', '吉林', '黑龙江', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海', '台湾', '内蒙古', '广西', '西藏', '宁夏', '新疆', '北京', '天津', '上海', '重庆', '香港', '澳门']):
matched_country = '中国'
# 进行省份匹配
matched_province = next((province['name'] for province in cn_data if province['name'] in line_data[2]), '0')
else:
# 进行国家匹配
matched_country = next((country['cname'] for country in countries_data if country['cname'] in country_name), '0')
# 进行省份匹配
matched_province = next((state['cname'] for state in states_data if state['cname'] and state['cname'] in line_data[2]), '0')
if not matched_province:
continue
# 进行城市匹配
matched_city = next((city['cname'] for city in cities_data if city['cname'] in ' '.join(line_data[2:])), '0')
# 进行运营商匹配
matched_lsp_idc = next((lsp['cname'] for lsp in lsp_idc_data if lsp['cname'] in ' '.join(line_data[3:])), '0')
if matched_lsp_idc == '0':
matched_lsp = next((lsp['cname'] for lsp in lsp_data if lsp['cname'] in ' '.join(line_data[3:])), '0')
else:
matched_lsp = matched_lsp_idc
# 写入匹配结果
output_file.write(f"{ip_range[0]}|{ip_range[1]}|{matched_country}|0|{matched_province}|{matched_city}|{matched_lsp}\n")
bar.next()
bar.finish()
print('ip.merge.txt文件已生成')
except Exception as e:
print(f" | An error occurred: {str(e)}")
print('ip.merge.txt文件已生成')
bar.finish()