Python dns.resolver() Examples

The following are 30 code examples for showing how to use dns.resolver(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module dns , or try the search function .

Example 1
Project: privdns   Author: mhelwig   File: privdns.py    License: 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
Project: designate   Author: openstack   File: impl_gdnsd.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, *a, **kw):
        """Configure the backend"""
        super(GdnsdBackend, self).__init__(*a, **kw)

        self._gdnsd_cmd_name = cfg.CONF[CFG_GROUP_NAME].gdnsd_cmd_name
        LOG.info("gdnsd command: %r", self._gdnsd_cmd_name)
        self._confdir_path = cfg.CONF[CFG_GROUP_NAME].confdir_path
        self._zonedir_path = os.path.join(self._confdir_path, 'zones')
        LOG.info("gdnsd conf directory: %r", self._confdir_path)
        self._resolver = dns.resolver.Resolver(configure=False)
        self._resolver.timeout = SOA_QUERY_TIMEOUT
        self._resolver.lifetime = SOA_QUERY_TIMEOUT
        self._resolver.nameservers = [
            cfg.CONF[CFG_GROUP_NAME].query_destination
        ]
        LOG.info("Resolvers: %r", self._resolver.nameservers)
        self._check_dirs(self._zonedir_path) 
Example 3
Project: fierce   Author: mschwager   File: test_fierce.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_recursive_query_basic_failure(self):
        resolver = dns.resolver.Resolver()
        domain = dns.name.from_text('example.com.')
        record_type = 'NS'

        with unittest.mock.patch.object(fierce, 'query', return_value=None) as mock_method:
            result = fierce.recursive_query(resolver, domain, record_type=record_type)

        expected = [
            unittest.mock.call(resolver, 'example.com.', record_type, tcp=False),
            unittest.mock.call(resolver, 'com.', record_type, tcp=False),
            unittest.mock.call(resolver, '', record_type, tcp=False),
        ]

        mock_method.assert_has_calls(expected)
        assert result is None 
Example 4
Project: fierce   Author: mschwager   File: test_fierce.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_recursive_query_long_domain_failure(self):
        resolver = dns.resolver.Resolver()
        domain = dns.name.from_text('sd1.sd2.example.com.')
        record_type = 'NS'

        with unittest.mock.patch.object(fierce, 'query', return_value=None) as mock_method:
            result = fierce.recursive_query(resolver, domain, record_type=record_type)

        expected = [
            unittest.mock.call(resolver, 'sd1.sd2.example.com.', record_type, tcp=False),
            unittest.mock.call(resolver, 'sd2.example.com.', record_type, tcp=False),
            unittest.mock.call(resolver, 'example.com.', record_type, tcp=False),
            unittest.mock.call(resolver, 'com.', record_type, tcp=False),
            unittest.mock.call(resolver, '', record_type, tcp=False),
        ]

        mock_method.assert_has_calls(expected)
        assert result is None 
Example 5
Project: fierce   Author: mschwager   File: test_fierce.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_recursive_query_basic_success(self):
        resolver = dns.resolver.Resolver()
        domain = dns.name.from_text('example.com.')
        record_type = 'NS'
        good_response = unittest.mock.MagicMock()
        side_effect = [
            None,
            good_response,
            None,
        ]

        with unittest.mock.patch.object(fierce, 'query', side_effect=side_effect) as mock_method:
            result = fierce.recursive_query(resolver, domain, record_type=record_type)

        expected = [
            unittest.mock.call(resolver, 'example.com.', record_type, tcp=False),
            unittest.mock.call(resolver, 'com.', record_type, tcp=False),
        ]

        mock_method.assert_has_calls(expected)
        assert result == good_response 
Example 6
Project: fierce   Author: mschwager   File: test_fierce.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_find_nearby_basic(self):
        resolver = 'unused'
        ips = [
            ipaddress.IPv4Address('192.168.1.0'),
            ipaddress.IPv4Address('192.168.1.1'),
        ]
        side_effect = [
            [MockAnswer('sd1.example.com.')],
            [MockAnswer('sd2.example.com.')],
        ]

        with unittest.mock.patch.object(fierce, 'reverse_query', side_effect=side_effect):
            result = fierce.find_nearby(resolver, ips)

        expected = {
            '192.168.1.0': 'sd1.example.com.',
            '192.168.1.1': 'sd2.example.com.',
        }

        assert expected == result 
Example 7
Project: fierce   Author: mschwager   File: test_fierce.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_find_nearby_filter_func(self):
        resolver = 'unused'
        ips = [
            ipaddress.IPv4Address('192.168.1.0'),
            ipaddress.IPv4Address('192.168.1.1'),
        ]
        side_effect = [
            [MockAnswer('sd1.example.com.')],
            [MockAnswer('sd2.example.com.')],
        ]

        def filter_func(reverse_result):
            return reverse_result == 'sd1.example.com.'

        with unittest.mock.patch.object(fierce, 'reverse_query', side_effect=side_effect):
            result = fierce.find_nearby(resolver, ips, filter_func=filter_func)

        expected = {
            '192.168.1.0': 'sd1.example.com.',
        }

        assert expected == result 
Example 8
Project: yeti   Author: yeti-platform   File: resolve_hostnames.py    License: Apache License 2.0 6 votes vote down vote up
def mass_resolve(self, domains, num_threads=100):
        threads = []
        for _ in range(0, num_threads):
            logging.debug("Starting thread {}".format(_))
            t = threading.Thread(target=self.consumer)
            t.start()
            threads.append(t)

        for d in domains:
            logging.debug("Putting {} in resolver queue".format(d))
            self.queue.put((d.value, 'A'), True)
            # Avoid ns1.ns1.ns1.domain.com style recursions
            if d.value.count('.') <= 2:
                self.queue.put((d.value, 'NS'), True)

        for t in threads:
            t.join()

        return self.results 
Example 9
Project: lemur   Author: Netflix   File: dyn.py    License: Apache License 2.0 6 votes vote down vote up
def _has_dns_propagated(fqdn, token):
    txt_records = []
    try:
        dns_resolver = dns.resolver.Resolver()
        dns_resolver.nameservers = [get_authoritative_nameserver(fqdn)]
        dns_response = dns_resolver.query(fqdn, "TXT")
        for rdata in dns_response:
            for txt_record in rdata.strings:
                txt_records.append(txt_record.decode("utf-8"))
    except dns.exception.DNSException:
        metrics.send("has_dns_propagated_fail", "counter", 1, metric_tags={"dns": fqdn})
        return False

    for txt_record in txt_records:
        if txt_record == token:
            metrics.send("has_dns_propagated_success", "counter", 1, metric_tags={"dns": fqdn})
            return True

    return False 
Example 10
Project: RTA   Author: flipkart-incubator   File: subtakeover.py    License: Apache License 2.0 6 votes vote down vote up
def check_takeover(domain, target):
    dnsResolver = dns.resolver.Resolver()
    dnsResolver.nameservers = ['8.8.8.8', '8.8.4.4']
    try:
        # Query the DNS resolver to check if subdomain is a CNAME
        answers = dnsResolver.query(target, 'CNAME')
        # Query whois
        for rdata in answers:
            output = '{:s}'.format(rdata.target)
            # If scope is/not in output splash some crap out
            if not domain in output:
                return output
    # To solve those "BLAH SUBDOMAIN IS NO CNAME" errors
    except dns.resolver.NoAnswer:
        pass
    except dns.resolver.NXDOMAIN:
        pass
    return 0 
Example 11
Project: dynatrace-api   Author: Dynatrace   File: dns_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __call__(self):
            """Execute the test step.

            Overrides the base class implementation.
            """
            self.set_started()

            self.resolver = dns.resolver.Resolver()
            self.resolver.nameserver = self._get_nameservers()
            self.logger.info('Querying name servers of {} started'.format(self.hostname))
            start_time = datetime.now()
            query_result = self.resolver.query(self.hostname, 'A')
            end_time = datetime.now()
            self.set_passed()
            self.logger.info('Querying name servers of {} finished successfully; found IPs: {}'
                             .format(self.hostname, ', '.join([str(rdata) for rdata in query_result])))
            self.duration = end_time - start_time 
Example 12
Project: MalPipe   Author: silascutler   File: DNSResolve.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        md = ProcessorDescription(
            module_name="DNSResolver",
            description="Resolve inbound domains",
            authors=["Silas Cutler"],
            version="0.1"
        )
        Processor.__init__(self, md)
        self.types = ['domains']
        self.parse_settings()
        self.dns = dns.resolver.Resolver()
        self.dns.nameservers = self.nameservers
        self.dns.timeout = 2
        self.dns.lifetime = 2

    # Module Settings 
Example 13
Project: cloud_enum   Author: initstring   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def dns_lookup(nameserver, name):
    """
    This function performs the actual DNS lookup when called in a threadpool
    by the fast_dns_lookup function.
    """
    res = dns.resolver.Resolver()
    res.timeout = 10
    res.nameservers = [nameserver]

    try:
        res.query(name)
        # If no exception is thrown, return the valid name
        return name
    except dns.resolver.NXDOMAIN:
        return ''
    except dns.exception.Timeout:
        print("    [!] DNS Timeout on {}. Investigate if there are many"
              " of these.".format(name)) 
Example 14
Project: TrustTrees   Author: mandatoryprogrammer   File: dns.py    License: Apache License 2.0 6 votes vote down vote up
def _dns_query(target_hostname, query_type, target_nameserver):
    res = dns.resolver.Resolver(configure=False)
    res.nameservers = [target_nameserver]
    result = res.query(
        qname=target_hostname,
        rdtype=query_type,
        raise_on_no_answer=False,
    )
    return result 
Example 15
Project: TrustTrees   Author: mandatoryprogrammer   File: dns.py    License: Apache License 2.0 6 votes vote down vote up
def _try_to_get_first_ip_for_hostname(hostname):
    """
    :returns: string
    e.g.
        "1.2.3.4" or ""
    """
    try:
        answer = _dns_query(
            hostname,
            query_type='A',
            target_nameserver=secrets.choice(global_state.RESOLVERS),
        )
        if answer.rrset:
            return str(answer.rrset[0])
    except (
        dns.resolver.NoNameservers,
        dns.resolver.NXDOMAIN,
        dns.resolver.Timeout,
        dns.resolver.YXDOMAIN,
    ):
        pass
    return '' 
Example 16
Project: ldapdomaindump   Author: dirkjanm   File: __init__.py    License: MIT License 6 votes vote down vote up
def lookupComputerDnsNames(self):
        dnsresolver = dns.resolver.Resolver()
        dnsresolver.lifetime = 2
        ipdef = attrDef.AttrDef('ipv4')
        if self.config.dnsserver != '':
            dnsresolver.nameservers = [self.config.dnsserver]
        for computer in self.computers:
            try:
                answers = dnsresolver.query(computer.dNSHostName.values[0], 'A')
                ip = str(answers.response.answer[0][0])
            except dns.resolver.NXDOMAIN:
                ip = 'error.NXDOMAIN'
            except dns.resolver.Timeout:
                ip = 'error.TIMEOUT'
            except (LDAPAttributeError, LDAPCursorError):
                ip = 'error.NOHOSTNAME'
            #Construct a custom attribute as workaround
            ipatt = attribute.Attribute(ipdef, computer, None)
            ipatt.__dict__['_response'] = ip
            ipatt.__dict__['raw_values'] = [ip]
            ipatt.__dict__['values'] = [ip]
            #Add the attribute to the entry's dictionary
            computer._state.attributes['IPv4'] = ipatt

    #Create a dictionary of all operating systems with the computer accounts that are associated 
Example 17
Project: PyFunceble   Author: funilrys   File: dns.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, dns_server=None, lifetime=3, tcp=False):
        self.given_dns_server = dns_server
        self.resolver = self.__get_resolver(dns_server)

        self.update_nameserver(dns_server)
        self.update_lifetime(lifetime)
        self.tcp = tcp

        PyFunceble.LOGGER.debug(
            f"DNS Resolver Nameservers: {self.resolver.nameservers}"
        )
        PyFunceble.LOGGER.debug(
            f"DNS Resolver (Nameservers) Port: {self.resolver.nameserver_ports}"
        )
        PyFunceble.LOGGER.debug(f"DNS Resolver Port: {self.resolver.port}")
        PyFunceble.LOGGER.debug(f"DNS Resolver timeout: {self.resolver.timeout}")
        PyFunceble.LOGGER.debug(f"DNS Resolver lifetime: {self.resolver.lifetime}")
        PyFunceble.LOGGER.debug(f"DNS Resolver over TCP: {self.tcp}")

        PyFunceble.INTERN["dns_lookup"] = {
            "resolver": self.resolver,
            "given_dns_server": dns_server,
        } 
Example 18
Project: designate   Author: openstack   File: test_handler.py    License: Apache License 2.0 5 votes vote down vote up
def _get_soa_answer(self, serial):
        text = "\n".join(ANSWER) % {"serial": str(serial)}
        msg = dns.message.from_text(text)
        name = dns.name.from_text('example.com.')
        answer = dns.resolver.Answer(name, dns.rdatatype.SOA,
                                     dns.rdataclass.IN, msg)
        return answer 
Example 19
Project: designate   Author: openstack   File: impl_bind9.py    License: Apache License 2.0 5 votes vote down vote up
def find_zone_serial(self, zone_name):
        LOG.debug("Finding %s", zone_name)
        resolver = dns.resolver.Resolver()
        resolver.nameservers = [cfg.CONF[CFG_GROUP_NAME].query_destination]
        try:
            rdata = resolver.query(zone_name, 'SOA')[0]
        except Exception:
            return None
        return rdata.serial 
Example 20
Project: designate   Author: openstack   File: impl_djbdns.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *a, **kw):
        """Configure the backend"""
        super(DjbdnsBackend, self).__init__(*a, **kw)
        conf = cfg.CONF[CFG_GROUP_NAME]

        self._resolver = dns.resolver.Resolver(configure=False)
        self._resolver.timeout = SOA_QUERY_TIMEOUT
        self._resolver.lifetime = SOA_QUERY_TIMEOUT
        self._resolver.nameservers = [conf.query_destination]
        self._masters = [utils.split_host_port(ns)
                         for ns in cfg.CONF['service:agent'].masters]
        LOG.info("Resolvers: %r", self._resolver.nameservers)
        LOG.info("AXFR masters: %r", self._masters)
        if not self._masters:
            raise exceptions.Backend("Missing agent AXFR masters")

        self._tcpclient_cmd_name = conf.tcpclient_cmd_name
        self._axfr_get_cmd_name = conf.axfr_get_cmd_name

        # Directory where data.cdb lives, usually /var/lib/djbdns/root
        tinydns_root_dir = os.path.join(conf.tinydns_datadir, 'root')

        # Usually /var/lib/djbdns/root/data.cdb
        self._tinydns_cdb_filename = os.path.join(tinydns_root_dir, 'data.cdb')
        LOG.info("data.cdb path: %r", self._tinydns_cdb_filename)

        # Where the agent puts the zone datafiles,
        # usually /var/lib/djbdns/datafiles
        self._datafiles_dir = datafiles_dir = os.path.join(
            conf.tinydns_datadir,
            'datafiles')
        self._datafiles_tmp_path_tpl = os.path.join(datafiles_dir, "%s.ztmp")
        self._datafiles_path_tpl = os.path.join(datafiles_dir, "%s.zonedata")
        self._datafiles_path_glob = self._datafiles_path_tpl % '*'

        self._check_dirs(tinydns_root_dir, datafiles_dir) 
Example 21
Project: designate   Author: openstack   File: impl_djbdns.py    License: Apache License 2.0 5 votes vote down vote up
def find_zone_serial(self, zone_name):
        """Query the local resolver for a zone
        Times out after SOA_QUERY_TIMEOUT
        """
        LOG.debug("Finding %s", zone_name)
        try:
            rdata = self._resolver.query(
                zone_name, rdtype=dns.rdatatype.SOA)[0]
            return rdata.serial
        except Exception:
            return None 
Example 22
Project: designate   Author: openstack   File: networking_test.py    License: Apache License 2.0 5 votes vote down vote up
def _setup_resolver(self, timeout=1):
        resolver = dns.resolver.Resolver(configure=False)
        resolver.timeout = timeout
        resolver.lifetime = timeout
        resolver.nameservers = [self.ns_ipaddr]
        self.resolver = resolver 
Example 23
Project: designate   Author: openstack   File: networking_test.py    License: Apache License 2.0 5 votes vote down vote up
def query_a_record(self, record_name, timeout=3):
        try:
            answer = self.resolver.query(record_name, 'A')
            if answer.rrset:
                return answer.rrset[0].address
        except Exception:
            return None 
Example 24
Project: designate   Author: openstack   File: networking_test.py    License: Apache License 2.0 5 votes vote down vote up
def query_soa(self, zone_name, timeout=3):
        try:
            soa_answer = self.resolver.query(zone_name, 'SOA')
            soa_serial = soa_answer[0].serial
            return soa_serial
        except Exception:
            return None 
Example 25
Project: designate   Author: openstack   File: networking_test.py    License: Apache License 2.0 5 votes vote down vote up
def probe_resolver(self, timeout=600):
        """Probe the local resolver in a dedicated thread until all
        goals have been achieved or timeout occours
        """
        assert not self.prober_is_running
        self.prober_can_stop = False
        self.prober_start_time = time.time()
        self.prober_timeout_time = self.prober_start_time + timeout
        self._prober_thread = Thread(target=self._probe_resolver)
        self._prober_thread.daemon = True
        self._prober_thread.start() 
Example 26
Project: ParadoxIP150v2   Author: Tertiush   File: client.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found.')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 27
Project: fierce   Author: mschwager   File: test_fierce.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_query_nxdomain(self):
        resolver = dns.resolver.Resolver()
        domain = dns.name.from_text('example.com.')

        with unittest.mock.patch.object(resolver, 'query', side_effect=dns.resolver.NXDOMAIN()):
            result = fierce.query(resolver, domain)

        assert result is None 
Example 28
Project: fierce   Author: mschwager   File: test_fierce.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_query_no_nameservers(self):
        resolver = dns.resolver.Resolver()
        domain = dns.name.from_text('example.com.')

        with unittest.mock.patch.object(resolver, 'query', side_effect=dns.resolver.NoNameservers()):
            result = fierce.query(resolver, domain)

        assert result is None 
Example 29
Project: fierce   Author: mschwager   File: test_fierce.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_find_nearby_empty(self):
        resolver = 'unused'
        ips = []

        result = fierce.find_nearby(resolver, ips)
        expected = {}

        assert expected == result 
Example 30
Project: privdns   Author: mhelwig   File: privdns.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def quickcheck(resolver):
    for cidr in private_networks:
        network = ipaddress.ip_network(str(cidr))
        hosts = network.hosts()
        ip = hosts.__next__()
        print("[*] Checking network " + cidr)
        result, answer = resolve(resolver,ip,True)
        if args.outfile:
            write_file(outfile,custom_ns,ip,result)
        if result in (1,2,3,4): #skip timeouts
            print("    * Nameserver responded, further checks ")
            if result == 1:
                print("[+] Entry found in nameserver " + str(custom_ns) + " for " + str(ip) + " : " + answer)
            for i in range(1,args.max_queries):
                ip = hosts.__next__()
                result, answer = resolve(resolver,ip,True)
                if args.outfile:
                    write_file(outfile,custom_ns,ip,result,answer)
                if result == 1:
                    print("[+] Entry found in nameserver " + str(custom_ns) + " for " + str(ip) + " : " + answer)
        else:
            print("    - No response, timeout or denied")
            if args.outfile:
                write_file(outfile,custom_ns,ip,result,answer)


# Resolve nameserver