Python dns.resolver.nameservers() Examples
The following are 30
code examples of dns.resolver.nameservers().
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
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: amplispy.py From AmpliSpy with GNU General Public License v3.0 | 8 votes |
def mech_ops(): br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('user-agent', select_UA()), ('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')] try: response = br.open("http://public-dns.info//nameservers.txt") except Exception as e: print "\n[" + t.red("!") + "]Critical, could not open public-dns.info" print "[" + t.green("+") + "]The following status code was recieved:" print "\n %s" % (e) sys.exit(1) result = response.read() proc = result.rstrip().split('\n') return proc # If args, read list, else fetch
Example #2
Source File: blockcheck.py From blockcheck with MIT License | 7 votes |
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: dnask.py From cyber-security-framework with MIT License | 6 votes |
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 #4
Source File: dns-queue.py From dns-parallel-prober with GNU General Public License v3.0 | 6 votes |
def run(self): resolver = dns.resolver.Resolver() resolver.timeout = self.dns_timeout # as per http://comments.gmane.org/gmane.comp.python.dnspython.user/144 resolver.lifetime = self.dns_timeout try: log.debug("{}: Resolving {} with nameserver {}".format( self.name, self.target, self.dns_server)) # it's a list resolver.nameservers = [self.dns_server, ] answer = resolver.query(self.target) for data in answer: out = '{} | {}'.format(self.target, data) self.res.append(out) # don't log to console, use file. # log.info(out) except dns.exception.Timeout as e: # we want to know if the DNS server is barfing errmsg = "{}: {}".format(self.target, e) self.err.append(errmsg) # log.warn(errmsg) except dns.exception.DNSException as e: log.debug("Error in thread {} when querying {}: {}".format( self.name, self.target, e))
Example #5
Source File: subbrute.py From subtake with GNU General Public License v2.0 | 6 votes |
def run(self): #Every user will get a different set of resovlers, this helps redistribute traffic. random.shuffle(self.resolver_list) if not self.verify(self.resolver_list): #This should never happen, inform the user. sys.stderr.write('Warning: No nameservers found, trying fallback list.\n') #Try and fix it for the user: self.verify(self.backup_resolver) #End of the resolvers list. try: self.resolver_q.put(False, timeout = 1) except: pass #Only add the nameserver to the queue if we can detect wildcards. #Returns False on error.
Example #6
Source File: subbrute.py From Yuki-Chan-The-Auto-Pentest with MIT License | 6 votes |
def run(self): #Every user will get a different set of resovlers, this helps redistribute traffic. random.shuffle(self.resolver_list) if not self.verify(self.resolver_list): #This should never happen, inform the user. sys.stderr.write('Warning: No nameservers found, trying fallback list.\n') #Try and fix it for the user: self.verify(self.backup_resolver) #End of the resolvers list. try: self.resolver_q.put(False, timeout = 1) except: pass #Only add the nameserver to the queue if we can detect wildcards. #Returns False on error.
Example #7
Source File: subbrute.py From BillCipher with GNU General Public License v3.0 | 6 votes |
def verify(self, nameserver_list): added_resolver = False for server in nameserver_list: if self.time_to_die: #We are done here. break server = server.strip() if server: self.resolver.nameservers = [server] try: #test_result = self.resolver.query(self.most_popular_website, "A") #should throw an exception before this line. if True:#test_result: #Only add the nameserver to the queue if we can detect wildcards. if(self.find_wildcards(self.target)):# and self.find_wildcards(".com") #wildcards have been added to the set, it is now safe to be added to the queue. #blocking queue, this process will halt on put() when the queue is full: self.add_nameserver(server) added_resolver = True else: trace("Rejected nameserver - wildcard:", server) except Exception as e: #Rejected server :( trace("Rejected nameserver - unreliable:", server, type(e)) return added_resolver
Example #8
Source File: subbrute.py From BillCipher with GNU General Public License v3.0 | 6 votes |
def run(self): #Every user will get a different set of resovlers, this helps redistribute traffic. random.shuffle(self.resolver_list) if not self.verify(self.resolver_list): #This should never happen, inform the user. sys.stderr.write('Warning: No nameservers found, trying fallback list.\n') #Try and fix it for the user: self.verify(self.backup_resolver) #End of the resolvers list. try: self.resolver_q.put(False, timeout = 1) except: pass #Only add the nameserver to the queue if we can detect wildcards. #Returns False on error.
Example #9
Source File: url.py From Vxscan with Apache License 2.0 | 6 votes |
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 #10
Source File: dnsutils.py From treadmill with Apache License 2.0 | 6 votes |
def make_resolver(dns_server=None): """Returns DNS resolver.""" resolver = dns.resolver.Resolver() # handle dns host and port override if dns_server: if dns_server[0] and all(dns_server[0]): resolver.nameservers = [socket.gethostbyname(host) for host in dns_server[0]] if dns_server[1]: resolver.port = dns_server[1] return resolver # Code from dyndns/resolve.py # TODO: remove once dyndns project is opensourced
Example #11
Source File: subbrute.py From ITWSV with MIT License | 6 votes |
def run(self): #Every user will get a different set of resovlers, this helps redistribute traffic. random.shuffle(self.resolver_list) if not self.verify(self.resolver_list): #This should never happen, inform the user. sys.stderr.write('Warning: No nameservers found, trying fallback list.\n') #Try and fix it for the user: self.verify(self.backup_resolver) #End of the resolvers list. try: self.resolver_q.put(False, timeout = 1) except: pass #Only add the nameserver to the queue if we can detect wildcards. #Returns False on error.
Example #12
Source File: amplispy.py From AmpliSpy with GNU General Public License v3.0 | 6 votes |
def query(address): dnsserver = address resolver = dns.resolver.Resolver() resolver.nameservers = [dnsserver] try: answer = resolver.query(args.url, "A") return True except dns.resolver.NoNameservers: return False except dns.resolver.NoAnswer: return False except dns.resolver.NXDOMAIN: return False except dns.exception.Timeout: return False # Sort
Example #13
Source File: subDomainsBrute.py From ZeroScan with MIT License | 6 votes |
def _test_server(self, server): resolver = dns.resolver.Resolver() resolver.lifetime = resolver.timeout = 10.0 try: resolver.nameservers = [server] answers = resolver.query('public-dns-a.baidu.com') # test lookup a existed domain if answers[0].address != '180.76.76.76': raise Exception('incorrect DNS response') try: resolver.query('test.bad.dns.lijiejie.com') # Non-existed domain test with open('bad_dns_servers.txt', 'a') as f: f.write(server + '\n') self._print_msg('[+] Bad DNS Server found %s' % server) except: self.dns_servers.append(server) self._print_msg('[+] Check DNS Server %s < OK > Found %s' % (server.ljust(16), len(self.dns_servers))) except: self._print_msg('[+] Check DNS Server %s <Fail> Found %s' % (server.ljust(16), len(self.dns_servers)))
Example #14
Source File: subbrute.py From Sublist3r with GNU General Public License v2.0 | 6 votes |
def verify(self, nameserver_list): added_resolver = False for server in nameserver_list: if self.time_to_die: #We are done here. break server = server.strip() if server: self.resolver.nameservers = [server] try: #test_result = self.resolver.query(self.most_popular_website, "A") #should throw an exception before this line. if True:#test_result: #Only add the nameserver to the queue if we can detect wildcards. if(self.find_wildcards(self.target)):# and self.find_wildcards(".com") #wildcards have been added to the set, it is now safe to be added to the queue. #blocking queue, this process will halt on put() when the queue is full: self.add_nameserver(server) added_resolver = True else: trace("Rejected nameserver - wildcard:", server) except Exception as e: #Rejected server :( trace("Rejected nameserver - unreliable:", server, type(e)) return added_resolver
Example #15
Source File: dnask.py From cyber-security-framework with MIT License | 6 votes |
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 #16
Source File: resolver.py From blacklist-rkn-tool with GNU General Public License v3.0 | 6 votes |
def __init__(self, cfg, transact, reporter, code_id): logger.info('Resolver init') self.code_id = code_id self.transact = transact self.cfg = cfg self.reporter = reporter self.domain_sql = self.reporter.domain_rollback_sql(0, 'ignore') self.dns_servers = str(cfg.DNS()).split(' ') self.resolvers = [dns.resolver.Resolver(configure=False) for i in range(len(self.dns_servers))] for resolver, dns_server in zip(self.resolvers, self.dns_servers): resolver.nameservers = [dns_server] resolver.timeout = self.cfg.QueryTimeout() resolver.lifetime = self.cfg.QueryTimeout() logger.info('Resolver history.id: %s', self.code_id)
Example #17
Source File: utils.py From parsedmarc with Apache License 2.0 | 6 votes |
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 #18
Source File: fierce.py From fierce with GNU General Public License v3.0 | 6 votes |
def update_resolver_nameservers(resolver, nameservers, nameserver_filename): """ Update a resolver's nameservers. The following priority is taken: 1. Nameservers list provided as an argument 2. A filename containing a list of nameservers 3. The original nameservers associated with the resolver """ if nameservers: resolver.nameservers = nameservers elif nameserver_filename: nameservers = get_stripped_file_lines(nameserver_filename) resolver.nameservers = nameservers else: # Use original nameservers pass return resolver
Example #19
Source File: test_filesystem.py From fierce with GNU General Public License v3.0 | 6 votes |
def test_update_resolver_nameservers_prefer_nameservers_over_file(self): nameserver_filename = os.path.join("directory", "nameservers") nameservers = ['192.168.1.1', '192.168.1.2'] contents = textwrap.dedent(""" nameserver1 nameserver2 nameserver3 """.strip()) self.fs.create_file( nameserver_filename, contents=contents ) resolver = dns.resolver.Resolver() result = fierce.update_resolver_nameservers( resolver, nameservers, nameserver_filename ) expected = nameservers assert expected == result.nameservers
Example #20
Source File: test_filesystem.py From fierce with GNU General Public License v3.0 | 6 votes |
def test_update_resolver_nameservers_no_nameserver_use_file(self): nameserver_filename = os.path.join("directory", "nameservers") nameservers = [] contents = textwrap.dedent(""" nameserver1 nameserver2 nameserver3 """.strip()) self.fs.create_file( nameserver_filename, contents=contents ) resolver = dns.resolver.Resolver() result = fierce.update_resolver_nameservers( resolver, nameservers, nameserver_filename ) expected = contents.split() assert expected == result.nameservers
Example #21
Source File: update_ddns_dnsmadeeasy.py From ddns-tools with MIT License | 6 votes |
def get_dns_ip(name=None, target='A'): name = name or RECORD_NAME bits = name.split('.') while bits: try: ns = str(dns.resolver.query('.'.join(bits), 'NS')[0]) except: bits.pop(0) else: ns = socket.gethostbyname(ns) resolver = dns.resolver.Resolver() resolver.nameservers = [ns] q = resolver.query(name, target) ip = str(q[0]).strip() return ip error('Could not get the authoritative name server for {0}.'.format(name))
Example #22
Source File: checkdmarc.py From checkdmarc with Apache License 2.0 | 5 votes |
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 #23
Source File: client.py From script.elementum.burst with Do What The F*ck You Want To Public License | 5 votes |
def ResolvePublic(host): try: log.debug("Custom DNS resolving with public DNS for: %s" % host) resolver = dns.resolver.Resolver() resolver.nameservers = dns_public_list answer = resolver.query(host, 'A') return answer.rrset.items[0].address except: return
Example #24
Source File: checkdmarc.py From checkdmarc with Apache License 2.0 | 5 votes |
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 #25
Source File: checkdmarc.py From checkdmarc with Apache License 2.0 | 5 votes |
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 #26
Source File: checkdmarc.py From checkdmarc with Apache License 2.0 | 5 votes |
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, timeout=timeout) 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: testbuild.py From netflix-proxy with MIT License | 5 votes |
def get_public_ip(): resolver = dns.resolver.Resolver() resolver.nameservers=[gethostbyname('resolver1.opendns.com')] return str(resolver.query('myip.opendns.com', 'A').rrset[0])
Example #28
Source File: client.py From script.elementum.burst with Do What The F*ck You Want To Public License | 5 votes |
def ResolveOpennic(host): try: log.debug("Custom DNS resolving with public DNS for: %s" % host) resolver = dns.resolver.Resolver() resolver.nameservers = dns_opennic_list answer = resolver.query(host, 'A') return answer.rrset.items[0].address except: return
Example #29
Source File: hook.py From letsencrypt-rackspace-hook with Apache License 2.0 | 5 votes |
def _has_dns_propagated(name, token): """ Verify that the challenge DNS record exists on Rackspace's nameservers. Keyword arguments: name -- domain name that needs a challenge record token -- the challenge text that LetsEncrypt expects to find in DNS """ successes = 0 for dns_server in rackspace_dns_servers: # We want to query Rackspace's DNS servers directly resolver.nameservers = [dns_server] # Retrieve all available TXT records that match our query try: dns_response = resolver.query(name, 'txt') except dns.exception.DNSException as error: return False # Loop through the TXT records to find one that matches our challenge text_records = [record.strings[0] for record in dns_response] for text_record in text_records: if text_record == token: successes += 1 # We need a successful check from BOTH DNS servers to move forward if successes == 2: logger.info(" + Challenge record found!") return True else: return False
Example #30
Source File: subbrute.py From subtake with GNU General Public License v2.0 | 5 votes |
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