本文整理汇总了Python中dns.resolver.Resolver.lifetime方法的典型用法代码示例。如果您正苦于以下问题:Python Resolver.lifetime方法的具体用法?Python Resolver.lifetime怎么用?Python Resolver.lifetime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dns.resolver.Resolver
的用法示例。
在下文中一共展示了Resolver.lifetime方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: reverse_dns_lookup
# 需要导入模块: from dns.resolver import Resolver [as 别名]
# 或者: from dns.resolver.Resolver import lifetime [as 别名]
def reverse_dns_lookup(input, timeout=3, server=''):
"""Perform a simple reverse DNS lookup, return results in a dictionary"""
assert _REVERSE_DNS_REGEX.search(
input), "Invalid address format: '{0}'".format(input)
resolver = Resolver()
resolver.timeout = float(timeout)
resolver.lifetime = float(timeout)
if server:
resolver.nameservers = [server]
try:
tmp = input.strip().split('.')
tmp.reverse()
inaddr = '.'.join(tmp) + ".in-addr.arpa"
records = resolver.query(inaddr, 'PTR')
return {
'name': records[0].to_text(),
'lookup': inaddr,
'error': '',
'addr': input,
}
except DNSException as e:
return {
'addrs': [],
'lookup': inaddr,
'error': repr(e),
'name': input,
}
示例2: dns6_lookup
# 需要导入模块: from dns.resolver import Resolver [as 别名]
# 或者: from dns.resolver.Resolver import lifetime [as 别名]
def dns6_lookup(input, timeout=3, server=''):
"""Perform a simple DNS lookup, return results in a dictionary"""
resolver = Resolver()
resolver.timeout = float(timeout)
resolver.lifetime = float(timeout)
if server:
resolver.nameservers = [server]
try:
records = resolver.query(input, 'AAAA')
return {'addrs': [ii.address for ii in records],
'error': '',
'name': input,
}
except DNSException as e:
return {'addrs': [],
'error': repr(e),
'name': input,
}
示例3: resolve
# 需要导入模块: from dns.resolver import Resolver [as 别名]
# 或者: from dns.resolver.Resolver import lifetime [as 别名]
def resolve(self, name, rrtype):
domain = dns.name.from_text(name)
dnsResolver = Resolver()
dnsResolver.lifetime = 5
# just an example
result = ''
try:
answers = dnsResolver.query(domain, rrtype)
for answer in answers:
if rrtype == 'MX':
result = answer.exchange
logging.debug('%s is %s' % (rrtype, result))
else:
raise Exception("unsupported type!")
except DNSException as ex:
logging.error("resolve() DNSException: %s" % ex.__class__)
raise Exception(ex.__class__)
except Exception as ex:
logging.error("resolve() exception: %s" % ex)
raise ex
return result
示例4: check_dns
# 需要导入模块: from dns.resolver import Resolver [as 别名]
# 或者: from dns.resolver.Resolver import lifetime [as 别名]
def check_dns(check, data):
check.addOutput("ScoreEngine: {} Check\n".format(check.getServiceName()))
check.addOutput("EXPECTED: Sucessful and correct query against the DNS server")
check.addOutput("OUTPUT:\n")
# Setup the resolver
resolv = Resolver()
resolv.nameservers = [data["HOST"]]
resolv.timeout = dns_config["timeout"]
resolv.lifetime = dns_config["lifetime"]
check.addOutput("Starting check...")
try:
# Query resolver
check.addOutput("Querying {HOST} for '{LOOKUP}'...".format(**data))
lookup = resolv.query(data["LOOKUP"], data["TYPE"])
found = False
for ans in lookup:
if str(ans) == data["EXPECTED"]:
found = True
else:
check.addOutput("NOTICE: DNS Server returned {}".format(ans))
if not found:
check.addOutput("ERROR: DNS Server did not respond with the correct IP")
return
# We're good!
check.setPassed()
check.addOutput("Check successful!")
except Exception as e:
check.addOutput("ERROR: {}: {}".format(type(e).__name__, e))
return
示例5: main
# 需要导入模块: from dns.resolver import Resolver [as 别名]
# 或者: from dns.resolver.Resolver import lifetime [as 别名]
def main():
# parse and check command line args
(options, args) = parse_args()
if (len(options.ensure_value('resolvers', [])) != 2
or len(args) != 1):
usage()
sys.exit()
if options.run_tests:
test()
sys.exit()
#copy arg values from parser output
resolver_ips = options.resolvers
verbose = options.verbose
question_file = args[0]
ttl_tolerance = int(options.ttl_tolerance)
side_by_side = options.side_by_side
#create dns resolvers (no dnssec for now)
#source_ips is a list parallel to resolvers that contains the IPv4 address
#to bind the query source address to -so you can control which interface the
#query comes from - useful for testing on a machine with multiple nics.
resolvers = []
source_ips = []
for resolver_ip in resolver_ips:
resolver = Resolver()
if resolver_ip.find('/') > 0:
parts = resolver_ip.split('/')
resolver.nameservers = [parts[0]]
source_ips.append(parts[1])
else:
resolver.nameservers = [resolver_ip]
source_ips.append(None)
resolver.retry_servfail = True
#resolver.use_edns(0, DO, 1200)
resolver.lifetime = 5
resolvers.append(resolver)
#only compare 2 resolvers for now
if len(resolvers) > 2:
print("only 2 resolvers allowed for now..., picking first 2")
resolvers = resolvers[:2]
#loop over the question input and compare the results from the resolvers
lineno = 0
for line in file(question_file):
#allow blank lines or lines that start with #
if len(line.strip()) == 0 or line.lstrip().startswith("#"):
continue
#assume anything else is a question: <name> <rdtype> [<rdclass>]
parts = line.strip().split(' ')
name = parts[0].strip()
rdtype = parts[1].strip()
rdclass = parts[2].strip() if len(parts) > 2 else 'IN'
lineno += 1
results = []
rtt_time = []
for resolver, source_ip in zip(resolvers, source_ips):
try:
start_time = time.time()
result = resolver.query(name, rdtype, rdclass, source=source_ip, raise_on_no_answer=False)
end_time = time.time()
results.append(result)
rtt_time.append(end_time - start_time)
except NXDOMAIN, nxd:
results.append(nxd)
rtt_time.append(-1)
except YXDOMAIN, yxd:
results.append(yxd)
rtt_time.append(-1)
except NoAnswer, noa:
results.append(noa)
rtt_time.append(-1)
示例6: dns_query
# 需要导入模块: from dns.resolver import Resolver [as 别名]
# 或者: from dns.resolver.Resolver import lifetime [as 别名]
def dns_query(input="", query_type="", server="", timeout=2.0):
"""A unified IPv4 & IPv6 DNS lookup interface; this is essentially just a wrapper around dnspython's API. When you query a PTR record, you can use an IPv4 or IPv6 address (which will automatically be converted into an in-addr.arpa name. This wrapper only supports a subset of DNS records: 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', and 'TXT'
Kwargs:
- input (str): A string containing the DNS record to lookup
- query_type (str): A string containing the DNS record type (SOA not supported)
- server (str): A string containing the fqdn or IP address of the dns server
- timeout (float): DNS lookup timeout duration (default: 2.0 seconds)
Returns:
A set() of :class:`~ccp_util.DNSResponse` instances
>>> from ciscoconfparse.ccp_util import dns_query
>>> dns_query('www.pennington.net', "A", "4.2.2.2")
set([<DNSResponse "A" result_str="65.19.187.2">])
>>> answer = dns_query('www.pennington.net', 'A', '4.2.2.2')
>>> str(answer.pop())
'65.19.187.2'
>>>
"""
valid_records = set(['A', 'AAAA', 'AXFR', 'CNAME', 'MX', 'NS', 'PTR',
'TXT'])
query_type = query_type.upper()
assert query_type in valid_records
assert server!=""
assert float(timeout)>0
assert input != ""
intput = input.strip()
retval = set([])
resolver = Resolver()
resolver.server = [socket.gethostbyname(server)]
resolver.timeout = float(timeout)
resolver.lifetime = float(timeout)
start = time.time()
if (query_type=="A") or (query_type=="AAAA"):
try:
answer = resolver.query(input, query_type)
duration = time.time() - start
for result in answer:
response = DNSResponse(query_type=query_type,
duration=duration,
input=input, result_str = str(result.address))
retval.add(response)
except DNSException as e:
duration = time.time() - start
response = DNSResponse(input=input,
duration=duration, query_type=query_type)
response.has_error = True
response.error_str = e
retval.add(response)
elif query_type=="AXFR":
"""This is a hack: return text of zone transfer, instead of axfr objs"""
_zone = zone.from_xfr(query.xfr(server, input, lifetime=timeout))
return [_zone[node].to_text(node) for node in _zone.nodes.keys()]
elif query_type=="CNAME":
try:
answer = resolver.query(input, query_type)
duration = time.time() - start
for result in answer:
response = DNSResponse(query_type=query_type,
duration=duration,
input=input, result_str = str(result.target))
retval.add(response)
except DNSException as e:
duration = time.time() - start
response = DNSResponse(input=input, duration=duration,
query_type=query_type)
response.has_error = True
response.error_str = e
retval.add(response)
elif query_type=="MX":
try:
answer = resolver.query(input, query_type)
duration = time.time() - start
for result in answer:
response = DNSResponse(query_type=query_type,
input=input, result_str = str(result.target))
response.preference = int(result.preference)
retval.add(response)
except DNSException as e:
duration = time.time() - start
response = DNSResponse(input=input, duration=duration,
query_type=query_type)
response.has_error = True
response.error_str = e
retval.add(response)
elif query_type=="NS":
try:
answer = resolver.query(input, query_type)
duration = time.time() - start
for result in answer:
response = DNSResponse(query_type=query_type,
duration=duration,
input=input, result_str = str(result.target))
retval.add(response)
except DNSException as e:
duration = time.time() - start
response = DNSResponse(input=input,
duration=duration, query_type=query_type)
#.........这里部分代码省略.........