Created
July 25, 2023 10:09
-
-
Save charSLee013/a1180522c452be3194e981ab48531c90 to your computer and use it in GitHub Desktop.
export netblocks from ipinfo.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import json | |
def extract_netblocks(json_file, output_file="netblocks.txt"): | |
try: | |
# 从JSON文件中读取数据 | |
with open(json_file, "r") as file: | |
data = file.read() | |
# 解析JSON数据 | |
parsed_data = json.loads(data) | |
# 遍历prefixes数组,筛选满足条件的netblock字段 | |
netblocks = [] | |
for prefix in parsed_data["prefixes"]: | |
# if prefix["domain"] == "cloudflare.com": | |
netblocks.append(prefix["netblock"]) | |
# 导出为文本文件 | |
with open(output_file, "w") as file: | |
file.write("\n".join(netblocks)) | |
print(f"提取并导出成功!已将netblocks保存到文件 {output_file} 中。") | |
except FileNotFoundError: | |
print("错误:找不到指定的JSON文件,请确保文件路径正确。") | |
except json.JSONDecodeError: | |
print("错误:JSON文件解析失败,请检查文件内容是否符合JSON格式。") | |
# 检查命令行参数 | |
if len(sys.argv) < 2: | |
print("错误:请输入JSON文件路径作为参数。比如说: python3 netblock_extractor.py data.json [-o]") | |
else: | |
json_file = sys.argv[1] | |
output_file = "netblocks.txt" | |
if len(sys.argv) > 3 and sys.argv[2] == "-o": | |
output_file = sys.argv[3] | |
extract_netblocks(json_file, output_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment