本方案適合撥號寬帶網絡環境,當檢測到公網IP地址變更時,可聯動自動觸發MQTT消息推送或郵件通知,實現動態IP的實時監控與告警。?
0x01? ? 代碼
import re
import time
import requestsdef 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 Nonedef 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 ipv4except Exception as e:print(e)return Nonedef 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:continuereturn "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_iptime.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