Python 脚本:获取公网 IPv4 和 IPv6 地址

本方案适合拨号宽带网络环境,当检测到公网IP地址变更时,可联动自动触发MQTT消息推送或邮件通知,实现动态IP的实时监控与告警。

0x01 代码

python 复制代码
import re
import time
import requests

def extract_ip(html):
    """用正则提取 IP(兼容各种格式)"""
    ip_match = re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', html)
    return ip_match.group(0) if ip_match else None

def get_public_ipv4_ip():
    try:
        # 设置伪装请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive'
        }
        response = requests.get("https://httpbin.org/ip", headers=headers)
        print(response.text)
        ipv4 = extract_ip(response.text)
        return ipv4
    except Exception as e:
        print(e)
        return None

def get_public_ipv6_ip():
    try:
        # 使用多个IP查询API(防止单个API失效)
        services = [
            'https://ident.me',
            'https://api.ipify.org',
            'https://ifconfig.me/ip',
        ]
        
        for url in services:
            try:
                response = requests.get(url, timeout=5)
                if response.status_code == 200:
                    print("fsdfsfs", response.content)
                    return response.text.strip()
            except requests.RequestException:
                continue

        return "Failed to get IP"
    except Exception as e:
        return f"Error: {e}"


def monitor_ip(interval=60):
    """定时检查IP变化(同时监控IPv4和IPv6)"""
    last_ips = {'v4': None, 'v6': None}

    while True:
        current_ips = {
            'v4': get_public_ipv4_ip(),
            'v6': get_public_ipv6_ip()
        }

        for ip_type in ['v4', 'v6']:
            current_ip = current_ips[ip_type]
            last_ip = last_ips[ip_type]

            if current_ip and current_ip != last_ip:
                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] IPv{ip_type} Changed: {current_ip}")
                last_ips[ip_type] = current_ip

        time.sleep(interval)

if __name__ == "__main__":
    print(f"Current Public IP: {get_public_ipv4_ip()} {get_public_ipv6_ip()} ")

    # 开启IP变化监控(每60秒检查一次)
    monitor_ip(interval=60)

0x02 运行效果:

0x99 参考:

Python 爬虫:requests 和 selenium 伪装 headers 和代理应对反爬机制 | XinanCSD.github.io

https://xinancsd.github.io/Python/anti_crawl_strategy.html

相关推荐
用户7227868123443 分钟前
python3.13 3.14 新特性 好好好
python
SunnyDays101121 分钟前
使用 Python 高效删除 Excel 重复数据(Excel 去重方法详解)
python·删除excel重复行·删除excel重复数据·excel去重·删除excel重复值
再__努力1点23 分钟前
【68】颜色直方图详解与Python实现
开发语言·图像处理·人工智能·python·算法·计算机视觉
Brian Xia25 分钟前
Nano-vLLM 源码分析(一) - 课程大纲
python·ai
Jinkxs29 分钟前
Java 架构 02:DDD 领域模型设计实战(限界上下文划分)
java·开发语言·架构
猪在黑魔纹里32 分钟前
解决VSCode无法高亮、解析numpy中的部分接口(如pi、deg2rad)
ide·vscode·python·numpy
爱笑的眼睛1141 分钟前
文本分类的范式演进:从统计概率到语言模型提示工程
java·人工智能·python·ai
星川皆无恙1 小时前
基于知识图谱+深度学习的大数据NLP医疗知识问答可视化系统(全网最详细讲解及源码/建议收藏)
大数据·人工智能·python·深度学习·自然语言处理·知识图谱
Tipriest_1 小时前
旋转矩阵,齐次变换矩阵,欧拉角,四元数等相互转换的常用代码C++ Python
c++·python·矩阵
毕设源码-钟学长1 小时前
【开题答辩全过程】以 基于PHP的家常菜谱教程网站为例,包含答辩的问题和答案
开发语言·php