使用青龙面板检测动态IPv4变更进行微信通知

有人问了,检测IP变更有什么用

那可太有用了,我举个栗子

比如说你使用的是家庭宽带部署项目

家庭宽带所给的IP是必定变动的

然后你又想要使用域名进行部署

但是域名解析只能是固定IPv4地址

你的动态IPv4什么时候被修改了都不知道

那么本文就是解决这个问题的


实践结果

e495e1e76520250406063607
42e8989a1a20250406063633
59dabf323320250406063641

直接推送到微信通知


首先,部署青龙面板(前期教程中有讲)

在我们的脚本管理中进行以下操作

d2b5ca33bd20250406063357

编辑脚本代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import os
import sys
from time import strftime

# 配置区 ================================================
WXPUSHER_TOKEN = ""  #修改为你的WxPusher token
USER_ID = ""  #修改为你的WxPusher用户ID
IP_FILE = "/ql/data/ip.txt"  # 新版青龙路径
IP_API = "https://admin.cccnm.cc/v4.php"  # 指定IP查询接口 可改
# ======================================================

def log(message):
    """记录带时间戳的日志"""
    print(f"[{strftime('%Y-%m-%d %H:%M:%S')}] {message}")

def get_public_ip():
    """获取公网IP(带多重验证)"""
    try:
        response = requests.get(IP_API, timeout=15)
        response.raise_for_status()
        
        ip = response.text.strip()
        # IP格式严格验证
        if not all([s.isdigit() and 0 <= int(s) <= 255 for s in ip.split('.')]):
            raise ValueError(f"无效IP格式: {ip}")
        return ip
    except Exception as e:
        log(f"获取IP失败: {str(e)}")
        return None

def send_wxpusher_notification(old_ip, new_ip):
    """发送微信通知(带重试机制)"""
    url = "https://wxpusher.zjiecode.com/api/send/message"
    headers = {"Content-Type": "application/json"}
    content = f"⚠️服务器IP变更通知\n旧IP: {old_ip}\n新IP: {new_ip}\n时间: {strftime('%Y-%m-%d %H:%M:%S')}"
    
    for attempt in range(3):  # 最大重试3次
        try:
            response = requests.post(
                url,
                json={
                    "appToken": WXPUSHER_TOKEN,
                    "content": content,
                    "contentType": 1,
                    "uids": [USER_ID],
                    "summary": 'IP变更通知'
                },
                headers=headers,
                timeout=10
            )
            result = response.json()
            if result.get("code") == 1000:
                log("微信通知发送成功")
                return True
            else:
                log(f"通知发送失败: {result.get('msg')}")
        except Exception as e:
            log(f"发送失败(尝试{attempt+1}/3): {str(e)}")
    return False

def init_ip_file():
    """初始化IP存储文件"""
    if not os.path.exists(IP_FILE):
        os.makedirs(os.path.dirname(IP_FILE), exist_ok=True)
        with open(IP_FILE, 'w') as f:
            f.write('')

def main():
    log("====== 开始执行IP检测 ======")
    init_ip_file()
    
    current_ip = get_public_ip()
    if not current_ip:
        log("无法获取有效IP,终止执行")
        sys.exit(1)
    
    # 读取历史IP
    old_ip = None
    with open(IP_FILE, 'r') as f:
        old_ip = f.read().strip() or None
    
    if old_ip != current_ip:
        log(f"检测到IP变更: {old_ip or '无记录'} → {current_ip}")
        if old_ip is not None:  # 首次运行不通知
            if not send_wxpusher_notification(old_ip, current_ip):
                log("警告:通知发送失败")
        
        # 更新IP记录
        with open(IP_FILE, 'w') as f:
            f.write(current_ip)
        log("已更新IP记录文件")
    else:
        log(f"IP未变化: {current_ip}")
    
    log("====== 执行完成 ======\n")

if __name__ == "__main__":
    main()

保存之后进行以下操作

d2b5ca33bd20250406063834

检测IP变动 命令/脚本

python3 /ql/data/scripts/ip_monitor.py

定时规则 这里可以修改为5,代表每五分钟检测一次

*/1 * * * *

点击确定即可


结语

其实还有其他办法解决,更可以进行全自动更换,推荐部署项目:DDNS-GO(科学上网)

本文代码产权归本站所有

© 版权声明
THE END
喜欢就支持一下吧
点赞8赞赏 分享