#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import json import urllib.request import urllib.error # 打印彩色输出的辅助函数 def print_color(text, color='green'): colors = { 'green': '\033[92m', 'yellow': '\033[93m', 'red': '\033[91m', 'blue': '\033[94m', 'end': '\033[0m' } print(f"{colors.get(color, '')}{text}{colors['end']}") # 获取IP信息 def get_ip_info(ip_addr): print_color(f"正在查询IP: {ip_addr} 的信息", 'blue') # 构建请求URL if ip_addr: url = f"https://whois.pconline.com.cn/ipJson.jsp?json=true&ip={ip_addr}" else: url = "https://whois.pconline.com.cn/ipJson.jsp?json=true" # 设置请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'zh-CN,zh;q=0.9' } request = urllib.request.Request(url, headers=headers) try: with urllib.request.urlopen(request, timeout=10) as response: # 获取状态码 status_code = response.getcode() print_color(f"HTTP状态码: {status_code}", 'blue') if status_code == 200: # 读取并解码响应内容 try: # 尝试使用GBK编码(中文网站常用) content = response.read().decode('gbk') except UnicodeDecodeError: try: # 尝试使用GB2312编码 content = response.read().decode('gb2312') except UnicodeDecodeError: # 最后尝试UTF-8 content = response.read().decode('utf-8') print_color(f"获取IP信息成功,响应长度: {len(content)} 字节", 'green') return True, content else: print_color(f"HTTP请求失败,状态码: {status_code}", 'red') return False, "" except urllib.error.URLError as e: print_color(f"网络请求失败: {str(e)}", 'red') return False, "" except Exception as e: print_color(f"发生未知错误: {str(e)}", 'red') return False, "" # 解析并打印IP信息JSON def parse_and_print_ip_info(json_response): print_color("开始解析IP信息JSON", 'yellow') print_color("原始JSON响应:", 'yellow') print(json_response) print() try: # 解析JSON data = json.loads(json_response) # 定义要提取的字段及其中文名称 fields = { "ip": "IP地址", "pro": "省份", "proCode": "省份代码", "city": "城市", "cityCode": "城市代码", "region": "区域", "regionCode": "区域代码", "addr": "详细地址", "err": "错误信息" } print_color("====== IP信息解析结果 ======", 'green') for field, name in fields.items(): if field in data: print(f"{name}: {data[field]}") else: print(f"{name}: 未找到") print_color("============================", 'green') # 如果有错误信息,打印错误 if 'err' in data and data['err']: print_color(f"注意: {data['err']}", 'red') except json.JSONDecodeError as e: print_color(f"JSON解析失败: {str(e)}", 'red') except Exception as e: print_color(f"解析过程中发生错误: {str(e)}", 'red') # 主函数 def main(): print_color("====== 太平洋IP查询API测试程序 ======", 'blue') print_color("此脚本使用Python标准库,无需安装额外依赖", 'yellow') print() # 获取用户输入的IP地址,如果没有则使用默认值 if len(sys.argv) > 1: test_ip = sys.argv[1] print_color(f"使用指定IP地址: {test_ip}", 'yellow') else: test_ip = "" print_color(f"未指定IP地址,将测试API是否可以自动识别本机IP", 'yellow') print() # 获取IP信息 success, response = get_ip_info(test_ip) if success and response: print() # 解析并打印IP信息 parse_and_print_ip_info(response) else: print_color("获取IP信息失败,请检查网络连接或IP地址", 'red') print() print_color("====== 测试完成 ======", 'blue') # 如果要查询本机公网IP,可以取消下面的注释 # print_color("提示: 要查询本机公网IP,请访问: https://www.ip138.com 或 https://ip.cn", 'yellow') if __name__ == "__main__": main()