Python dns.resolver() Examples
The following are 30
code examples of dns.resolver().
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
, or try the search function
.
Example #1
Source File: privdns.py From privdns with GNU Lesser General Public License v3.0 | 8 votes |
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: test_fierce.py From fierce with GNU General Public License v3.0 | 6 votes |
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 #3
Source File: subtakeover.py From RTA with Apache License 2.0 | 6 votes |
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 #4
Source File: dns_test.py From dynatrace-api with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #5
Source File: test_fierce.py From fierce with GNU General Public License v3.0 | 6 votes |
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 #6
Source File: test_fierce.py From fierce with GNU General Public License v3.0 | 6 votes |
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
Source File: dyn.py From lemur with Apache License 2.0 | 6 votes |
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 #8
Source File: resolve_hostnames.py From yeti with Apache License 2.0 | 6 votes |
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
Source File: test_fierce.py From fierce with GNU General Public License v3.0 | 6 votes |
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 #10
Source File: test_fierce.py From fierce with GNU General Public License v3.0 | 6 votes |
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 #11
Source File: DNSResolve.py From MalPipe with GNU General Public License v3.0 | 6 votes |
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 #12
Source File: utils.py From cloud_enum with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: dns.py From TrustTrees with Apache License 2.0 | 6 votes |
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 #14
Source File: dns.py From TrustTrees with Apache License 2.0 | 6 votes |
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 #15
Source File: dns.py From PyFunceble with Apache License 2.0 | 6 votes |
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 #16
Source File: impl_gdnsd.py From designate with Apache License 2.0 | 6 votes |
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 #17
Source File: __init__.py From ldapdomaindump with MIT License | 6 votes |
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 #18
Source File: dnslib.py From centinel with MIT License | 5 votes |
def __init__(self, domains=[], results={}, nameservers=[], exclude_nameservers=[], rtype="A", timeout=10, max_threads=100): """Constructor for the DNS query class Params: nameserver- the nameserver to use, defaults to the local resolver rtype- the record type to lookup (as text), by default A timeout- how long to wait for a response, by default 10 seconds """ self.domains = domains self.results = results self.rtype = rtype self.timeout = timeout self.max_threads = max_threads if len(nameservers) == 0: nameservers = dns.resolver.Resolver().nameservers # remove excluded nameservers if len(exclude_nameservers) > 0: for nameserver in exclude_nameservers: if nameserver in nameservers: nameservers.remove(nameserver) # include google nameserver if "8.8.8.8" not in nameservers: nameservers.append("8.8.8.8") self.nameservers = nameservers self.threads = [] # start point of port number to be used self.port = 30000 # create thread lock for port number index self.port_lock = threading.Lock()
Example #19
Source File: client.py From jarvis with GNU General Public License v2.0 | 5 votes |
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, try "pip install dnspython" or "pip3 install dnspython3".') if domain is None: domain = socket.getfqdn() domain = domain[domain.find('.') + 1:] try: rr = '_mqtt._tcp.%s' % domain if self._ssl: # 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)) # FIXME: 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 #20
Source File: client.py From Tautulli with GNU General Public License v3.0 | 5 votes |
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)) # FIXME: 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 #21
Source File: NSBSDPatching.py From azure-linux-extensions with Apache License 2.0 | 5 votes |
def __init__(self,logger,distro_info): super(NSBSDPatching,self).__init__(distro_info) self.logger = logger self.usr_flag = 0 self.mount_path = '/sbin/mount' try: import dns.resolver except ImportError: raise Exception("Python DNS resolver not available. Cannot proceed!") self.resolver = dns.resolver.Resolver() servers = [] getconf_cmd = "/usr/Firewall/sbin/getconf /usr/Firewall/ConfigFiles/dns Servers | tail -n +2" getconf_p = subprocess.Popen(getconf_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) output, _ = getconf_p.communicate() output = str(output) for server in output.split("\n"): if server == '': break server = server[:-1] # remove last '=' grep_cmd = "/usr/bin/grep '{}' /etc/hosts".format(server) + " | awk '{print $1}'" grep_p = subprocess.Popen(grep_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) ip, _ = grep_p.communicate() ip = str(ip).rstrip() servers.append(ip) self.resolver.nameservers = servers dns.resolver.override_system_resolver(self.resolver)
Example #22
Source File: test_config.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def setUp(self): super().setUp() # Ensure there's an initial DNS publication. Outside of tests this is # guaranteed by a migration. DNSPublication(source="Initial").save() # Allow test-local changes to configuration. self.useFixture(RegionConfigurationFixture()) # Immediately make DNS changes as they're needed. self.patch(dns_config_module, "DNS_DEFER_UPDATES", False) # Create a DNS server. self.bind = self.useFixture(BINDServer()) # Use the dnspython resolver for at least some queries. self.resolver = dns.resolver.Resolver() self.resolver.nameservers = ["127.0.0.1"] self.resolver.port = self.bind.config.port patch_dns_config_path(self, self.bind.config.homedir) # Use a random port for rndc. patch_dns_rndc_port(self, allocate_ports("localhost")[0]) # This simulates what should happen when the package is # installed: # Create MAAS-specific DNS configuration files. parser = ArgumentParser() setup_dns.add_arguments(parser) setup_dns.run(parser.parse_args([])) # Register MAAS-specific DNS configuration files with the # system's BIND instance. parser = ArgumentParser() get_named_conf.add_arguments(parser) get_named_conf.run( parser.parse_args( ["--edit", "--config-path", self.bind.config.conf_file] ) ) # Reload BIND. self.bind.runner.rndc("reload")
Example #23
Source File: urlabuse.py From url-abuse with GNU Affero General Public License v3.0 | 5 votes |
def dns_resolve(self, url): cached = self._cache_get(url, 'dns') if cached is not None: return cached self.fex.decode(url) host = self.fex.get_host().lower() ipv4 = None ipv6 = None if self.is_ip(host): if ':' in host: try: socket.inet_pton(socket.AF_INET6, host) ipv6 = [host] except Exception: pass else: try: socket.inet_aton(host) ipv4 = [host] except Exception: pass else: try: ipv4 = [str(ip) for ip in dns.resolver.query(host, 'A')] except Exception: logging.debug("No IPv4 address assigned to: " + host) try: ipv6 = [str(ip) for ip in dns.resolver.query(host, 'AAAA')] except Exception: logging.debug("No IPv6 address assigned to: " + host) self._cache_set(url, (ipv4, ipv6), 'dns') return ipv4, ipv6
Example #24
Source File: urlabuse.py From url-abuse with GNU Affero General Public License v3.0 | 5 votes |
def try_resolve(self, url): self.fex.decode(url) host = self.fex.get_host().lower() if self.is_ip(host): return True, None try: ipaddr = dns.resolver.query(host, 'A') except Exception: reason = "DNS server problem. Check resolver settings." return False, reason if not ipaddr: reason = "Host " + host + " does not exist." return False, reason return True, None
Example #25
Source File: dns.py From PyFunceble with Apache License 2.0 | 5 votes |
def __get_dns_servers_from(self, inputed_dns): # pragma: no cover """ Given a list or an input representing dns servers, we ensure that we have a list of a string which represent an IP. :param input: The inputed DNS server(s). :type input: str, list, tuple :return: The list of dns server to use. :rtype: list """ if isinstance(inputed_dns, (list, tuple)): result = [] for dns_server in inputed_dns: result.extend(self.__get_dns_servers_from(dns_server)) return result result = [] try: if PyFunceble.Check(inputed_dns).is_domain(): result.extend( [x.address for x in dns.resolver.Resolver().query(inputed_dns)] ) else: result.append(inputed_dns) except DNSException: result.extend(dns.resolver.get_default_resolver().nameservers) return result
Example #26
Source File: dnsdump.py From adidnsdump with MIT License | 5 votes |
def get_dns_resolver(server): # Create a resolver object dnsresolver = dns.resolver.Resolver() # Is our host an IP? In that case make sure the server IP is used # if not assume lookups are working already try: socket.inet_aton(server) dnsresolver.nameservers = [server] except socket.error: pass return dnsresolver
Example #27
Source File: dns_utility.py From pentesting-multitool with GNU General Public License v3.0 | 5 votes |
def run(self, domain, record, filename): if filename is not None: file = open(filename, 'a') print("File opened\n" "Writing the information on the file..") ans = dns.resolver.query(domain, record) file.write(ans.response.to_text()) print("Done.") file.close() else: print('Getting information..') ans = dns.resolver.query(domain, record) print(ans.response.to_text())
Example #28
Source File: utils.py From maltese with GNU General Public License v3.0 | 5 votes |
def get_default_dnsserver(): default = dns.resolver.get_default_resolver() return default.nameservers[0]
Example #29
Source File: dns_interface.py From OrangeAssassin with Apache License 2.0 | 5 votes |
def _query(self, qname, qtype): self.log.debug("Querying %s %s", qname, qtype) if qtype == "PTR": qname = dns.reversename.from_address(qname) try: result = self._resolver.query(qname, qtype) self.log.debug("Got %s for %s %s", result, qname, qtype) return result except (dns.resolver.NoAnswer, dns.resolver.NoNameservers, dns.resolver.NXDOMAIN, dns.exception.Timeout) as e: self.log.warn("Failed to resolve %s (%s): %s", qname, qtype, e) return [] except (ValueError, IndexError, struct.error) as e: self.log.info("Invalid DNS entry %s (%s): %s", qname, qtype, e) return []
Example #30
Source File: dns_interface.py From OrangeAssassin with Apache License 2.0 | 5 votes |
def namerservers(self, nameservers): "set the nameservers for the resolver" self._resolver.nameservers = nameservers