本文整理汇总了Python中dns.resolver.nameservers方法的典型用法代码示例。如果您正苦于以下问题:Python resolver.nameservers方法的具体用法?Python resolver.nameservers怎么用?Python resolver.nameservers使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dns.resolver
的用法示例。
在下文中一共展示了resolver.nameservers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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.
示例2: parse_ip
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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
示例3: test_update_resolver_nameservers_no_nameserver_use_file
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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
示例4: test_update_resolver_nameservers_prefer_nameservers_over_file
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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
示例5: update_resolver_nameservers
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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
示例6: _get_a_record
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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 ""
示例7: get_reverse_dns
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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
示例8: __init__
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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.")
示例9: run
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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)
示例10: __init__
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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)
示例11: _test_server
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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)))
示例12: get_dns_ip
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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))
示例13: mech_ops
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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
示例14: query
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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
示例15: make_resolver
# 需要导入模块: from dns import resolver [as 别名]
# 或者: from dns.resolver import nameservers [as 别名]
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