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