脚本能自动查询IP归属地吗?

wen 实用脚本 5

本文目录导读:

脚本能自动查询IP归属地吗?

  1. 其他可用的免费IP查询API:
  2. 使用Shell脚本(curl/wget)查询:
  3. 注意事项:

是的,脚本完全可以自动查询IP归属地,你可以通过调用公开的IP地理信息API来实现。

以下是一个使用Python脚本查询IP归属地的示例,它使用了免费的 ip-api.com 服务(无需API密钥,但有频率限制):

import requests
import json
def get_ip_location(ip_address=None):
    """
    查询IP地址的归属地信息
    :param ip_address: IP地址字符串,默认为None(查询本机IP)
    :return: 包含归属地信息的字典
    """
    # 如果未提供IP,则查询本机IP
    if ip_address is None:
        url = 'http://ip-api.com/json/'
    else:
        url = f'http://ip-api.com/json/{ip_address}'
    try:
        # 发送请求
        response = requests.get(url, timeout=5)
        # 检查请求是否成功
        if response.status_code == 200:
            data = response.json()
            if data['status'] == 'success':
                return {
                    'ip': data['query'],
                    'country': data['country'],
                    'region': data['regionName'],
                    'city': data['city'],
                    'isp': data['isp'],
                    'org': data['org'],
                    'timezone': data['timezone'],
                    'latitude': data['lat'],
                    'longitude': data['lon']
                }
            else:
                return {'error': 'Query failed'}
        else:
            return {'error': f'HTTP {response.status_code}'}
    except Exception as e:
        return {'error': str(e)}
# 使用示例
if __name__ == '__main__':
    # 查询本机IP归属地
    my_location = get_ip_location()
    print("本机IP归属地:")
    for key, value in my_location.items():
        print(f"{key}: {value}")
    print("\n---\n")
    # 查询特定IP归属地(例如Google DNS)
    target_ip = '8.8.8.8'
    target_location = get_ip_location(target_ip)
    print(f"IP {target_ip} 的归属地:")
    for key, value in target_location.items():
        print(f"{key}: {value}")

运行该脚本需要安装 requests,可以通过以下命令安装:

pip install requests

其他可用的免费IP查询API:

  1. ip-api.com(如上例)

    无密钥,免费版每分钟限制45次请求

  2. ipinfo.io

    免费版每日5万次请求,需注册获取token

  3. 极速数据(国内服务)

    需注册获取API密钥


使用Shell脚本(curl/wget)查询:

如果你希望在终端中快速查询,也可以使用一行命令(Linux/macOS/WSL):

# 查询本机IP归属地
curl -s http://ip-api.com/json/ | python3 -m json.tool
# 查询特定IP
curl -s http://ip-api.com/json/8.8.8.8 | python3 -m json.tool

注意事项:

  • 频率限制:免费API通常有调用频率限制,批量查询时需添加延迟(time.sleep(1)
  • 数据准确性:不同服务商的数据可能略有差异
  • 隐私:如果脚本需要处理大量用户IP,建议使用有可靠隐私政策的付费服务

希望这个回答对您有帮助!如果还有其他具体需求(如批量查询、输出格式定制等),欢迎继续提问。

抱歉,评论功能暂时关闭!