定时更新dns记录

清明假期就要到了。有个要更新dns记录的事情要在假期早上做。为了在路上不受到影响,提前做一个定时任务,用于更新bind中的zone的记录,并发邮件给我。

下面是python的代码:

#!/usr/bin/env python3

import os
import datetime
import smtplib
from email.mime.text import MIMEText

# Configuration
ZONE_FILE = "internet.mydomain.zone"
BACKUP_DIR = "zone_backups"
sender="dns_record_update@mydomain.com"
receiver="me@mydomain.com"
smtpserver="smtp.mydomain.com"
smtpport=25

# 1. Create Backup Directory (if it doesn't exist)
if not os.path.exists(BACKUP_DIR):
    os.makedirs(BACKUP_DIR)

# 2. Backup the Zone File
backup_file = os.path.join(BACKUP_DIR, f"{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}_{ZONE_FILE}")
import shutil
shutil.copy2(ZONE_FILE, backup_file)
print(f"Zone file backed up to: {backup_file}")

# 3. Modify the Zone File
with open(ZONE_FILE, 'r') as f:
    lines = f.readlines()

current_date = datetime.datetime.now().strftime('%Y%m%d01')

for i, line in enumerate(lines):
    if 'serial' in line:
        lines[i] = lines[i].replace('2025032001', current_date)
    if 'transport' in line:
        lines[i] = lines[i].replace('transport',';transport')
lines.append("transport IN CNAME transport.xxxx.xx\n")

with open(ZONE_FILE, 'w') as f:
    f.writelines(lines)

# 4. Restart the Named Service
import subprocess
try:
    subprocess.run(['sudo', 'service', 'named', 'reload'], check=True)  # Or sudo service named restart
    print("Named service restarted.")
except subprocess.CalledProcessError as e:
    print(f"Error restarting named service: {e}")

print("All operations completed.")


#5. verify cname resolution
dig_output=subprocess.check_output(["dig","+short","transport.mydomain.com"]).decode("utf-8").strip()
nslookup_output=subprocess.check_output(["nslookup","transport.mydomain.com"]).decode("utf-8").strip()



emailbody=f"""
zone file modification completed successfully.

CNAME resolution (dig):

{dig_output}

CNAME resolution (nslookup):

{nslookup_output}

"""
message=MIMEText(f"zone file modificate -transport cname verification\n\n{emailbody}")
message['Subject']="dns record update"
message['From']=sender
message['To']=receiver

with smtplib.SMTP(smtpserver,smtpport) as server:
    server.sendmail(sender,receiver,message.as_string())

这里我的smtp服务器不需要登录。

测试后,发现可以了。那就要定时执行。 安装at命令,并启动atd服务。

dnf install at
sysemctl enable atd
service atd start
service atd status

定时执行测试:

echo "python update-record.py" | at 14:54

通过后,就定时到真正需要改变的时间点:

echo "python update-record.py" | at 09:00 next Saturday

确定命令输出的时间是需要变更的时间。

检查计划队列:

[root@server01]# atq
5	Sat Mar 29 09:00:00 2025 a root

详细查看要执行的代码信息:

进入/var/spool/at目录,就能看到一个文件名为a00005xxxx。用cat打开就知道这个第五条任务是什么了,如果新加了任务,那么文件名就为a00006xxxx这样的,以此类推。执行后,这个文件就会被清理掉。

| 访问量:
Table of Contents