注:本文部分内容由AI协助完成
功能:
检测当前公网IP是否改变:如果有改变,则向指定邮箱发送当前IP。适用于暂时还没有配置内网穿透或者ddns等服务的情况。
环境准备:
requests库
pip install requests
所需文件:
ip.txt;GetIP.py;RunIP.bat
ip.txt内容:
(空白即可)
GetIP.py内容:
import smtplib
import ssl
import requests
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def send_email(subject, body, to_emails, from_email, from_password, smtp_server, smtp_port, attachment_path):
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = ', '.join(to_emails)
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
if attachment_path:
try:
attachment = open(attachment_path, 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f"attachment; filename= {attachment_path.split('/')[-1]}")
msg.attach(part)
except Exception as e:
print(f"Failed to attach file: {e}")
try:
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
server.set_debuglevel(1)
server.login(from_email, from_password)
text = msg.as_string()
server.sendmail(from_email, to_emails, text)
print("邮件发送成功")
except smtplib.SMTPAuthenticationError as e:
print(f"Authentication error: {e.smtp_code} - {e.smtp_error}")
except smtplib.SMTPException as e:
print(f"SMTP error: {e}")
except Exception as e:
print(f"Failed to send email: {e}")
try:
response = requests.get('https://api.ipify.org?format=json')
response.raise_for_status()
ip_info = response.json()
ip = ip_info.get('ip')
except requests.RequestException as e:
print(f"获取公网IP时发生错误: {e}")
if ip:
with open('ip.txt', 'r', encoding='utf-8') as file:
if ip != file.read():
file.seek(0)
print(f"IP已更改!\n旧IP:{file.read()}\n新IP:{ip}")
subject = "IP已改变"
# 替换为你的邮件主题
body = "当前的IP地址为:"+ip
# 替换为你的邮件正文
to_emails = ["123456789@qq.com", "987654321@outlook.com"]
# 替换为收件人的电子邮件地址列表
from_email = "123321456654@163.com"
# 替换为你的电子邮件地址
from_password = "ABCDEFGHIJKLMN"
# 替换为你的授权码
attachment_path = None
# 替换为附件路径,如果不需要附件则设置为 None
smtp_server="smtp.163.com"
# 替换为你的smtp服务器
smtp_port=465
# 自定义 SMTP 服务器端口
send_email(subject, body, to_emails, from_email, from_password, smtp_server, smtp_port, attachment_path)
with open('ip.txt', 'w', encoding='utf-8') as file:
file.write(ip)
else:
print("IP不变")
else:
print("无法获取公网IP地址")
RunIP.bat内容:
@echo off
cd /d D:\IP
python GetIP.py
创建任务计划:
有问题欢迎讨论