将域名与DNS解析器名称匹配-Python

如何解决将域名与DNS解析器名称匹配-Python

我对Python还是很陌生,并且一直在从事这项工作,并且有一些附带项目可以使我的Plex Media Management任务自动化。

我正在尝试编写一个python脚本,该脚本允许我从csv文件中获取一组域列表,并将其与dns名称匹配:示例(使用“ NS”的Plex.tv将返回jeremy.ns.cloudflare .com)

我的主要目标是从csv中读取域列表

运行我的代码以将这些域与dns解析器名称匹配

将它们写到一个新的CSV文件中,然后将两者压缩在一起,这就是我的代码。

一路上我遇到一些问题。

  1. Visual Code不允许导入dns.resolver(这不是一个大问题,但是如果您知道此修复程序,那么它就不必从命令行运行它了)
  2. 将域匹配到其DNS解析器会引发错误“ AttributeError:'list'对象没有属性'is_absolute'”
import csv
import socket
import dns.resolver
import os
from os.path import dirname,abspath

# Setting Variables
current_path = dirname(abspath(__file__))
domainFName = '{0}/domains.csv'.format(current_path)
outputFile = '{0}/output.csv'.format(current_path)
dnsList = '{0}/list2.csv'.format(current_path)
case_list = []
fields = ['Domains','DNS Resolvers']
caseList = []
dnsResolve = []

# Read in all domains from csv into list
with open(domainFName,'r') as file:
    for line in csv.reader(file):
        case_list.append(line)

print(case_list)

# Match domains to the DNS Resolver Name
for domains in case_list:
    answer = dns.resolver.resolve(domains,'NS')
    server = answer.target
    dnsResolve.append(server)

# Write the dns Resolver names into a new csv file
with open(dnsList,'w',newline="") as r:
    writers = csv.writer(r)
    writers.writerows(caseList)      

# Write the domains and dns resolvers to new output csv
with open(outputFile,newline="") as f:
    writer = csv.writer(f)
    writer.writerow(fields)
    writer.writerow(zip(case_list,caseList))

exit()

感谢您的帮助

解决方法

与同事讨论后,我能够解决我的问题,仅出于此目的,如果有人要出于类似的需要使用此代码(我们将其用于DMARC),我将发布整个代码:

import dns.resolver 
import csv
import os
from os.path import dirname,abspath


# Setting Variables
current_path = dirname(abspath(__file__))
domainFName = '{0}/domains.csv'.format(current_path)
outputFile = '{0}/output.csv'.format(current_path)
dnsList = '{0}/dnslist.csv'.format(current_path)
backupCSV = '{0}/backup-output.csv'.format(current_path)
case_list = []
dns_list = []
fields = ['Domains','DNS Resolvers']
csv_output = zip(case_list,dns_list)
domainAmount = 0
rd = 00
dnresolve = 00
part = 0
percentL = []
percents = [10,20,30,40,50,60,70,80,90,95,96,97,98,99]
percentList = []
floatingList = []
floatPart = []
x = 00
keyAzure = 'azure'
keyCSC = 'csc'
 

while x < .99:
    x += .01
    floatingList.append(x)

# THIS IS THE CODE FOR WRITING CSV FILES INTO LISTS - LABELED AS #1
print("FILES MUST BE CSV,WILL RETURN AN ERROR IF NOT. LEAVE OFF .CSV")

# Here we will gather the input of which csv file to use. If none are entered,it will use domains.csv
print("Enter your output file name (if blank will use default):")
UserFile = str(input("Enter your filename: ") or "domains")
fullFile = UserFile + '.csv'
domainFName = fullFile.format(current_path)
# Here will will specify the output file name. If the file is not created,it will create it
# If the user enters not data,the default will be used,output.csv
print("Enter your output file name (if blank will use default):")
UserOutput = str(input("Enter your filename: ") or "output")
fullOutput = UserOutput + '.csv'
outputFIle = fullOutput.format(current_path)


# Read in all domains from csv into list
with open(domainFName,'r') as file:
    for line in csv.reader(file):
        case_list.append(line)
        domainAmount += 1
        
print("Starting the resolver:")
print("You have " + str(domainAmount) + " Domains to resolve:")
# THIS IS THE END OF THE CODE FOR WRITING CSV FILES INTO LISTS - LABELED AS #1

# THE CODE BELOW IS WORKING FOR FINDING THE DNS RESOLVERS - LABELED AS #2
# Function for matching domains to DNS resolvers
def dnsResolver (domain):
    try:
        answers = dns.resolver.resolve(domain,'NS')
        for server in answers:
            dns_list.append(server.target)   
    except:
        dns_list.append("Did Not Resolve")  
       
print("Now resolving domains to their DNS name:")
print("This will take a few minutes. Check out the progress bar for your status:")
print("I have resolved 0% Domains:")

# This code is for finding the percentages for the total amount of domains to find progress status
def percentageFinder(percent,whole):
    return (percent * whole) / 100

def percentGetter(part,whole):
    return (100 * int(part)/int(whole))   

for x in percents:
    percentList.append(int(percentageFinder(x,domainAmount)))
    percentL = percentList
#End code for percentage finding

for firstdomain in case_list:
    for domain in firstdomain:
        dnsResolver(domain)
        if dnsResolver != "Did Not Resolve":
            rd += 1
        else:
            dnresolve += 1
        # Using w+ to overwrite all Domain Names & 
        with open(dnsList,'w+',newline="") as r:
            writers = csv.writer(r)
            writers.writerows(dns_list)
        # This is used for showing the percentage of the matching you have done
        part += 1
        if part in percentL:
            total = int(percentGetter(part,domainAmount))
            print("I Have Resolved {}".format(total) + "%" + " Domains:")
        else:
            pass

        
        
print("Resolving has completed. Statistics Below:")
print("------------------------------------------")



print("You had " + str(rd) + " domains that resolved.")
print("You had " + str(dnresolve) + " domains that did NOT resolve")



# THIS IS THE END OF THE WORKING CODE - LABELED AS #2     
   
# Write the dns Resolver names into a new csv file
print("Now writing your domains & their DNS Name to an Output File:")

with open(outputFile,newline="\n") as f:
    writer = csv.writer(f,dialect='excel')
    writer.writerow(fields)
    for row in csv_output:
        writer.writerow(row)


print("Writing a backup CSV File")

# Using this to create a backup in case to contain all domains,and all resolvers
# If someone runs the script with a small list of domains,still want to keep a 
# running list of everything in case any questions arise.
# This is done by using 'a' instead of 'w' or 'w+' done above.
with open(backupCSV,'w',newline="") as f:
    writer = csv.writer(f,dialect='excel')
    writer.writerow(fields)
    for row in csv_output:
        writer.writerow(row)
print("Your backup is now done processing. Exiting program")

# Sort the files by keyword,in this case the domain being azure or csc
for r in dns_list:
    if keyAzure in r:
        for x in keyAzure:
            FileName = x
            print(FileName)

exit()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-