Python脚本实现动态IP检测并邮件通知
在远程办公场景中,常需通过VPN接入内网,并访问局域网中的特定设备。例如,目标主机B通过无线网络接入,其本地IP地址可能动态变化。为确保能持续通过共享路径(如\\IP\share)访问该主机,需实时掌握其当前IP地址。本文介绍一个基于Python 3的解决方案:自动获取本机内网IP并监测变更,一旦发现变动即通过电子邮件发送通知。
import socket
import smtplib
import json
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr, parseaddr
import threading
程序启动后首先获取当前设备的网络接口信息。由于目标设备运行Windows 7系统且使用Wi-Fi连接,其内网IP通常以10.开头。以下函数用于提取符合条件的IPv4地址:
def get_wifi_ip():
host_info = socket.gethostbyname_ex(socket.gethostname())
for ip in host_info[2]:
if ip.startswith("10."):
return ip
return None
接下来是邮件发送功能。程序从JSON格式的配置字符串中解析出邮箱相关参数,包括发件人地址、授权码、收件人地址及SMTP服务器地址。为保证中文支持和邮件头合规性,采用email模块进行封装。
def compose_address(address_string):
name, addr = parseaddr(address_string)
encoded_name = Header(name, 'utf-8').encode()
return formataddr((encoded_name, addr))
def send_ip_notification(config_json):
if not config_json or not isinstance(config_json, str):
return
try:
config = json.loads(config_json)
sender = config["from_addr"]
token = config["password"]
recipient = config["to_addr"]
smtp_host = config["smtp_server"]
current_ip = get_wifi_ip()
content = f"设备IP已更新至:{current_ip}\r\n"
message = MIMEText(content, 'plain', 'utf-8')
message['From'] = compose_address(f'监控服务 <{sender}>')
message['To'] = compose_address(f'管理员 <{recipient}>')
message['Subject'] = Header('警报:主机IP地址变更', 'utf-8')
client = smtplib.SMTP(smtp_host, 25)
client.set_debuglevel(1)
client.login(sender, token)
client.sendmail(sender, [recipient], message.as_string())
client.quit()
print(f"通知邮件已发送至 {recipient},当前IP为 {current_ip}")
except Exception as e:
print(f"邮件发送失败: {e}")
核心逻辑在于持续监控IP是否发生变化。程序使用threading.Timer实现周期性检查(每小时一次),比较前后两次获取的IP值,若不同则触发邮件提醒。
current_ip = ""
def monitor_ip_change(initial_ip):
global current_ip
latest_ip = get_wifi_ip()
if latest_ip != initial_ip:
print(f"IP变更 detected: 原IP={initial_ip}, 新IP={latest_ip}")
send_ip_notification(config_data)
current_ip = latest_ip
else:
print(f"IP无变化: 当前IP仍为 {initial_ip}")
# 设置下一轮检查(3600秒后)
timer = threading.Timer(3600.0, monitor_ip_change, args=(latest_ip,))
timer.start()
主程序入口负责初始化配置加载与首次状态记录。配置文件config存放于脚本同目录下,内容为JSON格式的邮件参数。
if __name__ == '__main__':
config_data = ""
with open('./config', 'r', encoding='utf-8') as file:
config_data = file.read().strip()
starting_ip = get_wifi_ip()
current_ip = starting_ip
monitor_ip_change(starting_ip)
该实现完成了基本需求,但仍存在改进空间:可引入日志模块替代控制台输出;将配置持久化至SQLite数据库以增强管理灵活性;拆分功能模块提升代码可维护性。此外,未来可扩展为支持多种通知方式(如微信、短信)或加入加密存储机制。