Python dns.resolver.query() Examples

The following are 30 code examples of dns.resolver.query(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dns.resolver , or try the search function .
Example #1
Source File: privdns.py    From privdns with GNU Lesser General Public License v3.0 8 votes vote down vote up
def resolve(resolver,ip, quiet=False):
    try:
        answer = resolver.query(ip.reverse_pointer,'ptr')
        if not quiet:
            print("[+] " + str(ip) + " : " + str(answer[0]))
        return 1, str(answer[0])
    except dns.resolver.NXDOMAIN:
        if not quiet:
            print("[.] Resolved but no entry for " + str(ip))
        return 2, None
    except dns.resolver.NoNameservers:
        if not quiet:
            print("[-] Answer refused for " + str(ip))
        return 3, None
    except dns.resolver.NoAnswer:
        if not quiet:
            print("[-] No answer section for " + str(ip))
        return 4, None
    except dns.exception.Timeout:
        if not quiet:
            print("[-] Timeout")
        return 5, None

# log output to file 
Example #2
Source File: blockcheck.py    From blockcheck with MIT License 7 votes vote down vote up
def _get_a_record(site, querytype='A', dnsserver=None):
    resolver = dns.resolver.Resolver()
    resolver.timeout = 5
    resolver.lifetime = 5

    if dnsserver:
        resolver.nameservers = [dnsserver]

    result = []
    while len(resolver.nameservers):
        try:
            resolved = resolver.query(site, querytype)
            print_debug(str(resolved.response))
            for item in resolved.rrset.items:
                result.append(item.to_text())
            return result

        except dns.exception.Timeout:
            print_debug("DNS Timeout for", site, "using", resolver.nameservers[0])
            resolver.nameservers.remove(resolver.nameservers[0])

    # If all the requests failed
    return "" 
Example #3
Source File: reverse_resolve.py    From recon-ng-marketplace with GNU General Public License v3.0 6 votes vote down vote up
def module_run(self, addresses):
        max_attempts = 3
        resolver = self.get_resolver()
        for address in addresses:
            attempt = 0
            while attempt < max_attempts:
                try:
                    addr = dns.reversename.from_address(address)
                    hosts = resolver.query(addr, 'PTR')
                except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
                    self.verbose(f"{address} => No record found.")
                except dns.resolver.Timeout:
                    self.verbose(f"{address} => Request timed out.")
                    attempt += 1
                    continue
                except dns.resolver.NoNameservers:
                    self.verbose(f"{address} => Invalid nameserver.")
                    #self.error('Invalid nameserver.')
                    #return
                else:
                    for host in hosts:
                        host = str(host)[:-1] # slice the trailing dot
                        self.insert_hosts(host, address)
                # break out of the loop
                attempt = max_attempts 
Example #4
Source File: dnask.py    From cyber-security-framework with MIT License 6 votes vote down vote up
def __init__(self):
        super().__init__()
        self.parser.add_argument("query", type=str, help="Query string.")
        self.parser.add_argument("-t", "--rdtype", type=str, default=1, help="Query type.")
        self.parser.add_argument("-c", "--rdclass", type=str, default=1, help="Query class.")
        self.parser.add_argument("-m", "--metaquery", action="store_true", help="Execute as MetaQuery.")
        self.parser.add_argument("-s", "--source", type=str, default=socket.gethostbyname(socket.gethostname()), help="Source address.")
        self.parser.add_argument("-sP", "--source-port", type=int, default=random.randint(1, 65535), help="Source port.")
        self.parser.add_argument("--tcp", action="store_true", help="Use TCP to make the query.")
        self.parser.add_argument("-ns", "--nameservers", nargs="+", type=str, help="A list of nameservers to query. Each nameserver is a string which contains the IP address of a nameserver.")
        self.parser.add_argument("-p", "--port", type=int, default=53, help="The port to which to send queries (Defaults to 53).")
        self.parser.add_argument("-T", "--timeout", type=int, default=8, help="The number of seconds to wait for a response from a server, before timing out.")
        self.parser.add_argument("-l", "--lifetime", type=int, default=8, help="The total number of seconds to spend trying to get an answer to the question. If the lifetime expires, a Timeout exception will occur.")
        self.parser.add_argument("-e", "--edns", type=int, default=-1, help="The EDNS level to use (Defaults to -1, no Edns).")
        self.parser.add_argument("-eF", "--edns-flags", type=int, help="The EDNS flags.")
        self.parser.add_argument("-eP", "--edns-payload", type=int, default=0, help="The EDNS payload size (Defaults to 0).")
        self.parser.add_argument("-S", "--want-dnssec", action="store_true", help="Indicate that DNSSEC is desired.")
        self.parser.add_argument("-f", "--flags", type=int, default=None, help="The message flags to use (Defaults to None (i.e. not overwritten)).")
        self.parser.add_argument("-r", "--retry-servfail", action="store_true", help="Retry a nameserver if it says SERVFAIL.")
        self.parser.add_argument("-R", "--one-rr-per-rrset", action="store_true", help="Put each RR into its own RRset (Only useful when executing MetaQueries).")
        self.parser.add_argument("--filename", type=argparse.FileType("r"), help="The filename of a configuration file in standard /etc/resolv.conf format. This parameter is meaningful only when I{configure} is true and the platform is POSIX.")
        self.parser.add_argument("--configure-resolver", action="store_false", help="If True (the default), the resolver instance is configured in the normal fashion for the operating system the resolver is running on. (I.e. a /etc/resolv.conf file on POSIX systems and from the registry on Windows systems.") 
Example #5
Source File: dnask.py    From cyber-security-framework with MIT License 6 votes vote down vote up
def run(self):
        arguments = self.arguments.__dict__
        nameservers = arguments.get("nameservers")
        resolver = dns.resolver.Resolver(arguments.get("filename"), arguments.get("configure_resolver"))
        resolver.set_flags(arguments.get("flags"))
        resolver.use_edns(arguments.get("edns"), arguments.get("edns_flags"), arguments.get("edns_payload"))
        if nameservers:
            resolver.nameservers = nameservers
        resolver.port = arguments.get("port")
        resolver.timeout = arguments.get("timeout")
        resolver.lifetime = arguments.get("lifetime")
        resolver.retry_servfail = arguments.get("retry_servfail")
        if arguments.pop("metaquery"):
            kwargs = {v: arguments.get(k) for k, v in {"rdclass": "rdclass", "edns": "use_edns", "want_dnssec": "want_dnssec", "edns_flags": "ednsflags", "edns_payload": "request_payload"}.items()}
            message = dns.message.make_query(arguments.get("query"), arguments.get("rdtype"), **kwargs)
            kwargs = {k: arguments.get(k) for k in ["timeout", "port", "source", "source_port", "one_rr_per_rrset"]}
            if arguments.get("tcp"):
                resp = dns.query.tcp(message, resolver.nameservers[0], **kwargs)
            else:
                resp = dns.query.udp(message, resolver.nameservers[0], **kwargs)
            print(resp)
        else:
            kwargs = {k: arguments.get(k) for k in ["rdtype", "rdclass", "tcp", "source", "source_port"]}
            answer = resolver.query(arguments.pop("query"), **kwargs)
            print(answer.response) 
Example #6
Source File: url.py    From Vxscan with Apache License 2.0 6 votes vote down vote up
def parse_ip(host):
    host = parse_host(host)
    # 根据domain得到ip 例如www.xxx.com 得到 x.x.x.x
    try:
        resolver = dns.resolver.Resolver()
        resolver.nameservers = ['1.1.1.1', '8.8.8.8']
        a = resolver.query(host, 'A')
        for i in a.response.answer:
            for j in i.items:
                if hasattr(j, 'address'):
                    if not re.search(r'1\.1\.1\.1|8\.8\.8\.8|127\.0\.0\.1|114\.114\.114\.114|0\.0\.0\.0', j.address):
                        return j.address
    except dns.resolver.NoAnswer:
        pass
    except Exception as e:
        logging.exception(e)
    return host 
Example #7
Source File: __init__.py    From ESD with GNU General Public License v3.0 6 votes vote down vote up
def transfer_info(self):
        ret_zones = list()
        try:
            nss = dns.resolver.query(self.domain, 'NS')
            nameservers = [str(ns) for ns in nss]
            ns_addr = dns.resolver.query(nameservers[0], 'A')
            # dnspython 的 bug,需要设置 lifetime 参数
            zones = dns.zone.from_xfr(dns.query.xfr(ns_addr, self.domain, relativize=False, timeout=2, lifetime=2), check_origin=False)
            names = zones.nodes.keys()
            for n in names:
                subdomain = ''
                for t in range(0, len(n) - 1):
                    if subdomain != '':
                        subdomain += '.'
                    subdomain += str(n[t].decode())
                if subdomain != self.domain:
                    ret_zones.append(subdomain)
            return ret_zones
        except BaseException:
            return [] 
Example #8
Source File: e164.py    From script.elementum.burst with Do What The F*ck You Want To Public License 6 votes vote down vote up
def query(number, domains, resolver=None):
    """Look for NAPTR RRs for the specified number in the specified domains.

    e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.'])
    """
    if resolver is None:
        resolver = dns.resolver.get_default_resolver()
    e_nx = dns.resolver.NXDOMAIN()
    for domain in domains:
        if isinstance(domain, string_types):
            domain = dns.name.from_text(domain)
        qname = dns.e164.from_e164(number, domain)
        try:
            return resolver.query(qname, 'NAPTR')
        except dns.resolver.NXDOMAIN as e:
            e_nx += e
    raise e_nx 
Example #9
Source File: util.py    From exchangelib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def peek(iterable):
    """Checks if an iterable is empty and returns status and the rewinded iterable

    Args:
      iterable:

    """
    from .queryset import QuerySet
    if isinstance(iterable, QuerySet):
        # QuerySet has __len__ but that evaluates the entire query greedily. We don't want that here. Instead, peek()
        # should be called on QuerySet.iterator()
        raise ValueError('Cannot peek on a QuerySet')
    if hasattr(iterable, '__len__'):
        # tuple, list, set
        return not iterable, iterable
    # generator
    try:
        first = next(iterable)
    except StopIteration:
        return True, iterable
    # We can't rewind a generator. Instead, chain the first element and the rest of the generator
    return False, itertools.chain([first], iterable) 
Example #10
Source File: hooks.py    From dnsrobocert with MIT License 6 votes vote down vote up
def _check_one_challenge(challenge: str, token: Optional[str]) -> bool:
    try:
        answers = resolver.query(challenge, "TXT")
    except (resolver.NXDOMAIN, resolver.NoAnswer):
        print("TXT {0} does not exist.".format(challenge))
        return False
    else:
        print("TXT {0} exists.".format(challenge))

    if token:
        validation_answers = [
            rdata
            for rdata in answers
            for txt_string in rdata.strings
            if txt_string.decode("utf-8") == token
        ]

        if not validation_answers:
            print("TXT {0} does not have the expected token value.".format(challenge))
            return False

        print("TXT {0} has the expected token value.")

    return True 
Example #11
Source File: util.py    From exchangelib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def chunkify(iterable, chunksize):
    """Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``.

    Args:
      iterable:
      chunksize:

    """
    from .queryset import QuerySet
    if hasattr(iterable, '__getitem__') and not isinstance(iterable, QuerySet):
        # tuple, list. QuerySet has __getitem__ but that evaluates the entire query greedily. We don't want that here.
        for i in range(0, len(iterable), chunksize):
            yield iterable[i:i + chunksize]
    else:
        # generator, set, map, QuerySet
        chunk = []
        for i in iterable:
            chunk.append(i)
            if len(chunk) == chunksize:
                yield chunk
                chunk = []
        if chunk:
            yield chunk 
Example #12
Source File: utils.py    From parsedmarc with Apache License 2.0 6 votes vote down vote up
def get_reverse_dns(ip_address, cache=None, nameservers=None, timeout=2.0):
    """
    Resolves an IP address to a hostname using a reverse DNS query

    Args:
        ip_address (str): The IP address to resolve
        cache (ExpiringDict): Cache storage
        nameservers (list): A list of one or more nameservers to use
        (Cloudflare's public DNS resolvers by default)
        timeout (float): Sets the DNS query timeout in seconds

    Returns:
        str: The reverse DNS hostname (if any)
    """
    hostname = None
    try:
        address = dns.reversename.from_address(ip_address)
        hostname = query_dns(address, "PTR", cache=cache,
                             nameservers=nameservers,
                             timeout=timeout)[0]

    except dns.exception.DNSException:
        pass

    return hostname 
Example #13
Source File: brute_hosts.py    From recon-ng-marketplace with GNU General Public License v3.0 6 votes vote down vote up
def module_run(self, domains):
        with open(self.options['wordlist']) as fp:
            words = fp.read().split()
        resolver = self.get_resolver()
        for domain in domains:
            self.heading(domain, level=0)
            wildcard = None
            try:
                answers = resolver.query(f"*.{domain}")
                wildcard = answers.response.answer[0][0]
                self.output(f"Wildcard DNS entry found for '{domain}' at '{wildcard}'.")
            except (dns.resolver.NoNameservers, dns.resolver.Timeout):
                self.error('Invalid nameserver.')
                continue
            except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
                self.verbose('No Wildcard DNS entry found.')
            self.thread(words, domain, resolver, wildcard) 
Example #14
Source File: axfr.py    From OneForAll with GNU General Public License v3.0 6 votes vote down vote up
def check(self):
        """
        check
        """
        resolver = utils.dns_resolver()
        try:
            answers = resolver.query(self.domain, "NS")
        except Exception as e:
            logger.log('ERROR', e.args)
            return
        nsservers = [str(answer) for answer in answers]
        if not len(nsservers):
            logger.log('ALERT', f'No name server record found for {self.domain}')
            return
        for nsserver in nsservers:
            self.axfr(nsserver) 
Example #15
Source File: fierce.py    From fierce with GNU General Public License v3.0 6 votes vote down vote up
def query(resolver, domain, record_type='A', tcp=False):
    try:
        resp = resolver.query(domain, record_type, raise_on_no_answer=False, tcp=tcp)
        if resp.response.answer:
            return resp

        # If we don't receive an answer from our current resolver let's
        # assume we received information on nameservers we can use and
        # perform the same query with those nameservers
        if resp.response.additional and resp.response.authority:
            ns = [
                rdata.address
                for additionals in resp.response.additional
                for rdata in additionals.items
            ]
            resolver.nameservers = ns
            return query(resolver, domain, record_type, tcp=tcp)

        return None
    except (dns.resolver.NXDOMAIN, dns.resolver.NoNameservers, dns.exception.Timeout):
        return None 
Example #16
Source File: get_domain_ip.py    From armory with GNU General Public License v3.0 6 votes vote down vote up
def run(domain):
    ips = []
    resolver = dns.resolver.Resolver()
    resolver.lifetime = resolver.timeout = 5.0

    try:
        answers = resolver.query(domain, "A")
        for a in answers:
            ips.append(a.address)
        return ips
    except Exception:
        # print("Regular DNS Not Resolved\n")
    # Temporarily disabling - seems to cause massive delays at times.

    #     pass
    # try:
    #    ips = [ str(i[4][0]) for i in socket.getaddrinfo(domain, 443) ] 
    #    return ips
    # except Exception:
    #    print("Unable to Resolve\n")
       return ips 
Example #17
Source File: checkdmarc.py    From checkdmarc with Apache License 2.0 5 votes vote down vote up
def get_spf_record(domain, nameservers=None, timeout=2.0):
    """
    Retrieves and parses an SPF record

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)
        timeout(float): Number of seconds to wait for an answer from DNS

    Returns:
        OrderedDict: An SPF record parsed by result

    Raises:
        :exc:`checkdmarc.SPFRecordNotFound`
        :exc:`checkdmarc.SPFIncludeLoop`
        :exc:`checkdmarc.SPFRedirectLoop`
        :exc:`checkdmarc.SPFSyntaxError`
        :exc:`checkdmarc.SPFTooManyDNSLookups`

    """
    record = query_spf_record(domain, nameservers=nameservers, timeout=timeout)
    record = record["record"]
    parsed_record = parse_spf_record(record, domain, nameservers=nameservers,
                                     timeout=timeout)
    parsed_record["record"] = record

    return parsed_record 
Example #18
Source File: subbrute.py    From subtake with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, target, record_type, resolver_q, resolver_list, wildcards):
        multiprocessing.Process.__init__(self, target = self.run)
        self.daemon = True
        signal_init()

        self.time_to_die = False
        self.resolver_q = resolver_q
        self.wildcards = wildcards
        #Do we need wildcards for other types of records?
        #This needs testing!
        self.record_type = "A"
        if record_type == "AAAA":
            self.record_type = record_type
        self.resolver_list = resolver_list
        resolver = dns.resolver.Resolver()
        #The domain provided by the user.
        self.target = target
        #1 website in the world,  modify the following line when this status changes.
        #www.google.cn,  I'm looking at you ;)
        self.most_popular_website = "www.google.com"
        #We shouldn't need the backup_resolver, but we we can use them if need be.
        #We must have a resolver,  and localhost can work in some environments.
        self.backup_resolver = resolver.nameservers + ['127.0.0.1', '8.8.8.8', '8.8.4.4']
        #Ideally a nameserver should respond in less than 1 sec.
        resolver.timeout = 1
        resolver.lifetime = 1
        try:
            #Lets test the letancy of our connection.
            #Google's DNS server should be an ideal time test.
            resolver.nameservers = ['8.8.8.8']
            resolver.query(self.most_popular_website, self.record_type)
        except:
            #Our connection is slower than a junebug in molasses
            resolver = dns.resolver.Resolver()
        self.resolver = resolver 
Example #19
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def _get_txt_records(domain, nameservers=None, timeout=2.0):
    """
    Queries DNS for TXT records

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)
        timeout(float): number of seconds to wait for an answer from DNS

    Returns:
        list: A list of TXT records

     Raises:
        :exc:`checkdmarc.DNSException`

    """
    try:
        records = _query_dns(domain, "TXT", nameservers=nameservers)
    except dns.resolver.NXDOMAIN:
        raise DNSException("The domain {0} does not exist".format(domain))
    except dns.resolver.NoAnswer:
        raise DNSException(
            "The domain {0} does not have any TXT records".format(domain))
    except Exception as error:
        raise DNSException(error)

    return records 
Example #20
Source File: checkdmarc.py    From checkdmarc with Apache License 2.0 5 votes vote down vote up
def _get_txt_records(domain, nameservers=None, timeout=2.0):
    """
    Queries DNS for TXT records

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)
        timeout(float): number of seconds to wait for an answer from DNS

    Returns:
        list: A list of TXT records

     Raises:
        :exc:`checkdmarc.DNSException`

    """
    try:
        records = _query_dns(domain, "TXT", nameservers=nameservers,
                             timeout=timeout)
    except dns.resolver.NXDOMAIN:
        raise DNSException("The domain {0} does not exist".format(domain))
    except dns.resolver.NoAnswer:
        raise DNSException(
            "The domain {0} does not have any TXT records".format(domain))
    except Exception as error:
        raise DNSException(error)

    return records 
Example #21
Source File: checkdmarc.py    From checkdmarc with Apache License 2.0 5 votes vote down vote up
def _get_a_records(domain, nameservers=None, timeout=2.0):
    """
    Queries DNS for A and AAAA records

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)
        timeout(float): number of seconds to wait for an answer from DNS

    Returns:
        list: A sorted list of IPv4 and IPv6 addresses

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    qtypes = ["A", "AAAA"]
    addresses = []
    for qt in qtypes:
        try:
            addresses += _query_dns(domain, qt, nameservers=nameservers,
                                    timeout=timeout)
        except dns.resolver.NXDOMAIN:
            raise DNSException("The domain {0} does not exist".format(domain))
        except dns.resolver.NoAnswer:
            # Sometimes a domain will only have A or AAAA records, but not both
            pass
        except Exception as error:
            raise DNSException(error)

    addresses = sorted(addresses)
    return addresses 
Example #22
Source File: brute_hosts.py    From recon-ng-marketplace with GNU General Public License v3.0 5 votes vote down vote up
def module_thread(self, word, domain, resolver, wildcard):
        max_attempts = 3
        attempt = 0
        while attempt < max_attempts:
            host = f"{word}.{domain}"
            try:
                answers = resolver.query(host)
            except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
                self.verbose(f"{host} => No record found.")
            except dns.resolver.Timeout:
                self.verbose(f"{host} => Request timed out.")
                attempt += 1
                continue
            else:
                # process answers
                if answers.response.answer[0][0] == wildcard:
                    self.verbose(f"{host} => Response matches the wildcard.")
                else:
                    for answer in answers.response.answer:
                        for rdata in answer:
                            if rdata.rdtype in (1, 5):
                                if rdata.rdtype == 1:
                                    address = rdata.address
                                    self.alert(f"{host} => (A) {address}")
                                    self.insert_hosts(host, address)
                                if rdata.rdtype == 5:
                                    cname = rdata.target.to_text()[:-1]
                                    self.alert(f"{host} => (CNAME) {cname}")
                                    self.insert_hosts(cname)
                                    # add the host in case a CNAME exists without an A record
                                    self.insert_hosts(host)
            # break out of the loop
            attempt = max_attempts 
Example #23
Source File: checkdmarc.py    From checkdmarc with Apache License 2.0 5 votes vote down vote up
def _get_mx_hosts(domain, nameservers=None, timeout=2.0):
    """
    Queries DNS for a list of Mail Exchange hosts

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)

    Returns:
        list: A list of ``OrderedDicts``; each containing a ``preference``
                        integer and a ``hostname``

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    hosts = []
    try:
        logging.debug("Checking for MX records on {0}".format(domain))
        answers = _query_dns(domain, "MX", nameservers=nameservers,
                             timeout=timeout)
        for record in answers:
            record = record.split(" ")
            preference = int(record[0])
            hostname = record[1].rstrip(".").strip().lower()
            hosts.append(OrderedDict(
                [("preference", preference), ("hostname", hostname)]))
        hosts = sorted(hosts, key=lambda h: (h["preference"], h["hostname"]))
    except dns.resolver.NXDOMAIN:
        raise DNSException("The domain {0} does not exist".format(domain))
    except dns.resolver.NoAnswer:
        pass
    except Exception as error:
        raise DNSException(error)
    return hosts 
Example #24
Source File: reverse_resolve.py    From recon-ng-marketplace with GNU General Public License v3.0 5 votes vote down vote up
def module_run(self, netblocks):
        max_attempts = 3
        resolver = self.get_resolver()
        for netblock in netblocks:
            self.heading(netblock, level=0)
            addresses = self.cidr_to_list(netblock)
            for address in addresses:
                attempt = 0
                while attempt < max_attempts:
                    try:
                        addr = dns.reversename.from_address(address)
                        hosts = resolver.query(addr,'PTR')
                    except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
                        self.verbose(f"{address} => No record found.")
                    except dns.resolver.Timeout:
                        self.verbose(f"{address} => Request timed out.")
                        attempt += 1
                        continue
                    except (dns.resolver.NoNameservers):
                        self.verbose(f"{address} => Invalid nameserver.")
                    else:
                        for host in hosts:
                            host = str(host)[:-1] # slice the trailing dot
                            self.insert_hosts(host, address)
                    # break out of the loop
                    attempt = max_attempts 
Example #25
Source File: dnstraceroute.py    From dnsdiag with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def ping(resolver, hostname, dnsrecord, ttl, src_ip, use_edns=False):
    global _ttl

    reached = False

    dns.query.socket_factory = CustomSocket
    _ttl = ttl
    if use_edns:
        resolver.use_edns(edns=0, payload=8192, ednsflags=dns.flags.edns_from_text('DO'))

    try:
        resolver.query(hostname, dnsrecord, source=src_ip, raise_on_no_answer=False)

    except dns.resolver.NoNameservers as e:
        if not quiet:
            print("no or bad response:", e)
        sys.exit(1)
    except dns.resolver.NXDOMAIN as e:
        if not quiet:
            print("Invalid hostname:", e)
        sys.exit(1)
    except dns.resolver.Timeout:
        pass
    except dns.resolver.NoAnswer:
        if not quiet:
            print("invalid answer")
    except SystemExit:
        pass
    except Exception as e:
        print("unxpected error: ", e)
        sys.exit(1)
    else:
        reached = True

    return reached 
Example #26
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def _get_nameservers(domain, nameservers=None, timeout=2.0):
    """
    Queries DNS for a list of nameservers

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)

    Returns:
        list: A list of ``OrderedDicts``; each containing a ``preference``
                        integer and a ``hostname``

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    answers = []
    try:

        answers = _query_dns(domain, "NS", nameservers=nameservers)
    except dns.resolver.NXDOMAIN:
        raise DNSException("The domain {0} does not exist".format(domain))
    except dns.resolver.NoAnswer:
        pass
    except Exception as error:
        raise DNSException(error)
    return answers 
Example #27
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def _get_mx_hosts(domain, nameservers=None, timeout=2.0):
    """
    Queries DNS for a list of Mail Exchange hosts

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)

    Returns:
        list: A list of ``OrderedDicts``; each containing a ``preference``
                        integer and a ``hostname``

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    hosts = []
    try:
        logging.debug("Checking for MX records on {0}".format(domain))
        answers = _query_dns(domain, "MX", nameservers=nameservers)
        for record in answers:
            record = record.split(" ")
            preference = int(record[0])
            hostname = record[1].rstrip(".").strip().lower()
            hosts.append(OrderedDict(
                [("preference", preference), ("hostname", hostname)]))
        hosts = sorted(hosts, key=lambda h: (h["preference"], h["hostname"]))
    except dns.resolver.NXDOMAIN:
        raise DNSException("The domain {0} does not exist".format(domain))
    except dns.resolver.NoAnswer:
        pass
    except Exception as error:
        raise DNSException(error)
    return hosts 
Example #28
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def _get_a_records(domain, nameservers=None, timeout=2.0):
    """
    Queries DNS for A and AAAA records

    Args:
        domain (str): A domain name
        nameservers (list): A list of nameservers to query
        (Cloudflare's by default)
        timeout(float): number of seconds to wait for an answer from DNS

    Returns:
        list: A sorted list of IPv4 and IPv6 addresses

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    qtypes = ["A", "AAAA"]
    addresses = []
    for qt in qtypes:
        try:
            addresses += _query_dns(domain, qt, nameservers=nameservers)
        except dns.resolver.NXDOMAIN:
            raise DNSException("The domain {0} does not exist".format(domain))
        except dns.resolver.NoAnswer:
            # Sometimes a domain will only have A or AAAA records, but not both
            pass
        except Exception as error:
            raise DNSException(error)

    addresses = sorted(addresses)
    return addresses 
Example #29
Source File: srv_resolver.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _resolve_uri(self, encapsulate_errors):
        try:
            results = resolver.query('_mongodb._tcp.' + self.__fqdn, 'SRV',
                                     lifetime=self.__connect_timeout)
        except Exception as exc:
            if not encapsulate_errors:
                # Raise the original error.
                raise
            # Else, raise all errors as ConfigurationError.
            raise ConfigurationError(str(exc))
        return results 
Example #30
Source File: util.py    From exchangelib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_valid_hostname(hostname, timeout):
    log.debug('Checking if %s can be looked up in DNS', hostname)
    resolver = dns.resolver.Resolver()
    resolver.timeout = timeout
    try:
        resolver.query(hostname)
    except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
        return False
    return True