菜单

Python脚本监控特定域名的IP地址变化


发布于 2024-07-19 / 35 阅读 / 0 评论 /
Python脚本监控特定域名的IP地址变化,并在变化时发送电子邮件通知。 1、邮箱配置 开启POP3/SMTP服务

Python脚本监控特定域名的IP地址变化,并在变化时发送电子邮件通知。

1、邮箱配置

开启POP3/SMTP服务

以163邮箱为例,https://mail.163.com/ 登录邮箱,打开设置,打开POP3/SMTP/IMAP

image-20240719210304747

授权码只会显示一次,复制保存,后续登录需要用到。

image-20240719210412119

2、代码实现

# -- coding:utf-8 --
import dns.resolver
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import time
from datetime import datetime
​
# # 获取当前时间
# now = datetime.now()
#
# # 格式化时间
# formatted_time = now.strftime('%Y-%m-%d %H:%M:%S')
#
# # 打印格式化后的时间
# print(formatted_time)
def get_domain_ips(domain):
    """获取域名的所有IP地址"""
    ips = []
    try:
        answers = dns.resolver.resolve(domain, 'A')
        for rdata in answers:
            ips.append(rdata.to_text())
    except dns.exception.DNSException as e:
        print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Error resolving domain: {e}")
    return ips
​
def send_email(subject, body, to_email, from_email, password, smtp_server, smtp_port):
    """发送电子邮件"""
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
​
    # 连接到SMTP服务器并发送电子邮件
    server = smtplib.SMTP_SSL(smtp_server, smtp_port)  # 使用SSL连接
    server.login(from_email, password)  # 登录到你的邮箱
    server.sendmail(from_email, to_email, msg.as_string())  # 发送邮件
    server.quit()  # 关闭连接
    #
    # server = smtplib.SMTP(smtp_server, smtp_port)
    # server.starttls()
    # server.login(from_email, password)
    # server.sendmail(from_email, to_email, msg.as_string())
    # server.quit()
​
def monitor_domain_ip_changes(domain, interval=60, to_email=None, from_email=None, password=None, smtp_server='smtp.163.com', smtp_port=465):
    """监测域名IP地址的变化,并在变化时发送电子邮件"""
    if not all([to_email, from_email, password]):
        print("Error: You need to provide to_email, from_email, and password to send email notifications.")
        return
​
    last_ips = get_domain_ips(domain)
    print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Initial IP addresses for {domain}: {last_ips}")
​
    while True:
        current_ips = get_domain_ips(domain)
        if set(current_ips) != set(last_ips):
            change_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            print(f"{change_time} IP addresses for {domain} have changed:")
            print(f"{change_time} Old: {last_ips}")
            print(f"{change_time} New: {current_ips}")
​
            # 构造电子邮件内容
            email_body = f"The IP addresses for {domain} have changed.\nOld: {last_ips}\nNew: {current_ips}"
            subject = f"IP Change Alert for {domain}"
​
            # 发送电子邮件
            send_email(subject, email_body, to_email, from_email, password, smtp_server, smtp_port)
​
            last_ips = current_ips
​
        time.sleep(interval)  # 等待指定的时间间隔(秒)
​
if __name__ == "__main__":
    domain_to_monitor = "rongtech.top"  # 替换为你要监测的域名
    to_email = "wu_fu_rong@163.com"  # 替换为接收邮件的邮箱地址
    from_email = "wu_fu_rong@163.com"  # 替换为发送邮件的邮箱地址
    password = "password"  # 替换为发送邮件邮箱的密码(授权码)
​
    monitor_domain_ip_changes(domain_to_monitor, to_email=to_email, from_email=from_email, password=password)

3、代码运行

上传代码到服务器使用screen运行

4、效果



是否对你有帮助?

评论