如何在网站(动态 DNS)的 IP 地址每次更改时收到通知电子邮件?

如何在网站(动态 DNS)的 IP 地址每次更改时收到通知电子邮件?

我每周的任务是从我公司站点的不同端口列表中监控IP地址,IP地址存储在txt文件中,例如:

http://name1.domain.net:port 
http://name2.domain.net:port2
http://name4.domain.net:port4

我过去常常使用 chrome 扩展程序“IP 地址和域信息”每 3 天手动获取一次 IP 地址并将更改粘贴到另一个 txt 文件中,但现在我的主管希望每 12 小时检查一次这些 IP 列表。

这个过程花费了我很多时间(大约 40 个地址,并且还在增加)。是否有任何程序或 bash 代码可以自动执行此过程,并且如果其中一些地址已关闭或获取另一个 IP 地址,只需向我发送电子邮件?例如,电子邮件内容应如下所示:

http://name4.domain.net:port4 - server "UP" - "New IPv4 address"
http://name1.domain.net:port4 - server "Down" - "IPv4 address"

答案1

嗯...对我来说现在是学校假期,我超级无聊今天,所以我决定编写一个 Python 脚本,它可以满足您的需求,并可以自动向您发送详细说明更改的电子邮件。它会每 12 小时检查一次您指定的站点的 IP urls。它应该可以工作。

这个答案可能属于 StackOverflow,但别管我 >:(

我添加了注释,详细说明了每个东西的作用

import requests, smtplib, time

# Put the urls of the servers you wanna check here (makes sure to specify http:// or https://)
urls = ['https://google.com', 'https://pigeonburger.xyz']
print("Checking websites:", str(urls))

def checkSites():
        while True:
            siteIPs = []

            # For each site in the list, get their IP and append it to another list for future checking. current_ips is what we'll be checking against.
            for site in urls:
                request = requests.get(site, stream=True)
                siteIPs.append([site, request.raw._connection.sock.getpeername()[0]])
                current_ips = siteIPs

            print("Current site IPs:", str(current_ips))

            # While the latest check of IPs is equal to the first check (i.e there has been no IP change). This loop will run every 12 hours (43200 seconds)
            while siteIPs == current_ips:
                print("No changes found. Checking the sites IPs again in 12 hours")
                time.sleep(43200)
                print("Checking sites IPs again......")
                siteIPs = []
                for site in urls:
                    request = requests.get(site, stream=True)
                    siteIPs.append([site, request.raw._connection.sock.getpeername()[0]])

            # Once the loop is broken, and a change is detected, find what site's IP was changed.
            print("An IP change(s) was detected! Locating the exact change now.....")
            def find_difference(x, y):
                list_difference = [i for i in x+y if i not in x]
                return list_difference

            site_diffs = find_difference(siteIPs, current_ips)

            # Generates a line to be included in the email detailing what the sites IP has changed to - a new line for each change.
            email_content = []
            for site_data in site_diffs:
                email_content.append(f"The IP of {site_data[0]} has changed to {site_data[1]}")
            print('\n'.join(email_content))

            # Send an email containing the info on the changes.
            print("Sending email containing the changes now......")
            sendMail('\n'.join(email_content))
            print("Email sent! Program will restart now.")


# This is the function that sends the email. Update the email addresses and SMTP server info to meet your needs.
def sendMail(content):
    sender = '[email protected]'
    receivers = ['[email protected]']

    message = f"""From: Server <[email protected]>
    To: Your email <[email protected]>
    Subject: Site IP Updated
    
    {content}
    """

    smtpObj = smtplib.SMTP('smtp.example.com', port=587)
    smtpObj.connect("smtp.example.com", port=587)
    smtpObj.ehlo()
    smtpObj.starttls()
    smtpObj.login("username", "password")
    smtpObj.sendmail(sender, receivers, message)

# Start
if __name__ == '__main__':
    checkSites()

对于任何阅读此文的人 - 如果脚本中存在任何潜在错误或有方法使其更高效,请告诉我。这不是我最好的代码哈哈

相关内容