如何为CNAME记录匹配最近前置$ORIGIN的rpz子串并拼接
处理DNS记录:匹配每条CNAME对应的最近$ORIGIN前缀
问题背景
现有一份DNS记录文件内容如下:
$ORIGIN .com.rpz.my.azure_domain.com azurebox1 CNAME azurebox1-dr.my.azure_domain.com $ORIGIN rpz.my.aws_domain.com awsbox1 CNAME awsbox1-dr.my.aws_domain.com awsbox2 CNAME awsbox2-dr.my.aws_domain.com awsbox3 CNAME awsbox3-dr.my.aws_domain.com $ORIGIN .org.rpz.my.gc_domain.com gcbox1 CNAME gcbox1-dr.my.gc_domain.com gcbox2 CNAME gcbox1-dr.my.gc_domain.com
需求是给每条CNAME记录的主机名拼接其最近前置的$ORIGIN行中包含rpz的后缀,最终输出格式示例:
- Azure相关:
azurebox1.com.rpz.my.azure_domain.com - AWS相关:
awsbox1.rpz.my.aws_domain.com - GC相关:
gcbox1.org.rpz.my.gc_domain.com
目前已通过以下代码读取文件:
f = open('current_records', 'r') records_string = f.readlines()
解决方案
核心思路是遍历记录时维护当前生效的$ORIGIN值,遇到新的$ORIGIN行就更新这个值,遇到CNAME行就用当前的$ORIGIN拼接主机名,无需提前捕获所有$ORIGIN行。
具体实现代码
# 初始化变量存储当前生效的ORIGIN后缀 current_origin = "" # 遍历每一行记录 for line in records_string: # 去除首尾空白字符,跳过空行 stripped_line = line.strip() if not stripped_line: continue # 处理$ORIGIN行:提取后缀,去掉开头可能存在的点 if stripped_line.startswith('$ORIGIN'): # 分割出ORIGIN值,取第二个元素 origin_value = stripped_line.split()[1] # 去掉开头的点(如果有的话) current_origin = origin_value.lstrip('.') continue # 处理CNAME行:提取主机名,拼接当前ORIGIN if 'CNAME' in stripped_line: # 分割出主机名,取第一个元素 hostname = stripped_line.split()[0] # 拼接并输出结果 full_domain = f"{hostname}.{current_origin}" print(full_domain)
代码说明
- 维护当前ORIGIN:用
current_origin变量实时记录最近一次遇到的$ORIGIN值,每次碰到新的$ORIGIN行就更新这个变量,自动覆盖旧值,保证始终是当前CNAME对应的最近前缀。 - 处理ORIGIN前缀的点:用
lstrip('.')去掉$ORIGIN值开头的点,避免拼接后出现hostname..xxx的错误格式。 - 提取CNAME主机名:通过分割行内容取第一个元素,得到需要拼接的主机名,再和当前
current_origin拼接成完整域名。
运行结果
执行代码后会输出:
azurebox1.com.rpz.my.azure_domain.com awsbox1.rpz.my.aws_domain.com awsbox2.rpz.my.aws_domain.com awsbox3.rpz.my.aws_domain.com gcbox1.org.rpz.my.gc_domain.com gcbox2.org.rpz.my.gc_domain.com
内容的提问来源于stack exchange,提问作者itinneed2022_1
相关产品推荐
相关产品推荐

