Python3-在写入文件之前过滤文本

时间:2019-01-14 21:58:48

标签: regex python-3.x filtering

这是我的main.py脚本调用的函数。

这是问题所在,我有一个包含IP地址列表的文件,并且查询此API,以便针对(url)变量查找给定IP的反向DNS查找。然后吐出“ response.text”。

在response.text文件中,

我没有找到96.x.x.x的DNS A记录

我得到的其他数据只是一个dns名称:'subdomain.domain.com'

我如何过滤我的结果以使其不针对每个“找不到(显示的内容)的DNS A记录”显示

#!/usr/bin/env python3
import requests
import pdb
#function to use hackertarget api for reverse dns lookup
def dns_finder(file_of_ips="endpointslist"):
    print('\n\n########## Finding DNS Names ##########\n')
    targets = open("TARGETS","w")
    with open (file_of_ips) as f:
        for line in f:
            line.strip()
            url = 'https://api.hackertarget.com/reverseiplookup/?q=' + line
            response = requests.get(url)
            #pdb.set_trace()
            hits = response.text
            print(hits)
            targets.write(hits)
            return hits

2 个答案:

答案 0 :(得分:0)

您可以使用re模块来检查响应,以确保它是有效的DNS主机名(使用正则表达式模式):

import re

# ... rest of your code

# before writing to targets file
if re.match('^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$', hits) is not None:
    targets.write(hits)

如果给定的字符串与正则表达式匹配,则re.match()函数将返回一个match对象。否则,它将返回None。因此,如果您检查以确保它不是None,则它应该与正则表达式匹配(即,它与DNS主机名的模式匹配)。您可以更改正则表达式或将检查抽象为更通用的isValidHit(hit),然后将要检查的所有功能(不仅仅是DNS主机名)放在那里。

注意

您要小心行targets = open("TARGETS","w")。这将打开文件进行写入,但是您需要在其他位置手动关闭文件并处理与IO相关的任何错误。

每当处理文件IO时,您都应尝试使用with open(filename) as blah:。它更安全,更容易维护。

编辑

找到here的IPv4地址的简单正则表达式。

添加更多有关正则表达式match函数的说明。

编辑2

我重新阅读了您的帖子,发现您实际上不是在寻找IPv4地址,而是DNS主机名...

在这种情况下,您只需将正则表达式模式切换为^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$Source for the DNS Hostname regex

答案 1 :(得分:0)

如果只想保留域名,

@Tim Klein的答案很好。但是,如问题中所述,如果您只想删除“未找到...的DNS A记录”之类的错误消息,则可以使用str.startswith方法:

#!/usr/bin/env python3
import requests
import pdb
#function to use hackertarget api for reverse dns lookup
def dns_finder(file_of_ips="endpointslist"):
    print('\n\n########## Finding DNS Names ##########\n')
    targets = open("TARGETS","w")
    with open (file_of_ips) as f:
        for line in f:
            line.strip()
            url = 'https://api.hackertarget.com/reverseiplookup/?q=' + line
            response = requests.get(url)
            #pdb.set_trace()
            hits = response.text
            print(hits)
            if not hits.startswith("No DNS A records found for"):
                targets.write(hits)
            return hits # why iterating if you return there ?
相关问题