本文整理汇总了Python中dns.exception方法的典型用法代码示例。如果您正苦于以下问题:Python dns.exception方法的具体用法?Python dns.exception怎么用?Python dns.exception使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dns
的用法示例。
在下文中一共展示了dns.exception方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_a_record
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [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 ""
示例2: _get_a_records
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def _get_a_records(sitelist, querytype='A', dnsserver=None, googleapi=False):
result = []
for site in sorted(sitelist):
try:
if googleapi:
responses = _get_a_record_over_google_api(site, querytype)
print_debug("Google API вернул {}".format(responses))
else:
responses = _get_a_record(site, querytype, dnsserver)
for item in responses:
result.append(item)
except dns.resolver.NXDOMAIN:
print("[!] Невозможно получить DNS-запись для домена {} (NXDOMAIN). Результаты могут быть неточными.".format(site))
except dns.resolver.NoAnswer:
print_debug("DNS NoAnswer:", site)
except dns.exception.DNSException as e:
print_debug("DNSException:", str(e))
really_bad_fuckup_happened()
return sorted(result)
示例3: _has_dns_propagated
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
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
示例4: to_digestable
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def to_digestable(self, origin=None):
"""Convert name to a format suitable for digesting in hashes.
The name is canonicalized and converted to uncompressed wire format.
@param origin: If the name is relative and origin is not None, then
origin will be appended to it.
@type origin: dns.name.Name object
@raises NeedAbsoluteNameOrOrigin: All names in wire format are
absolute. If self is a relative name, then an origin must be supplied;
if it is missing, then this exception is raised
@rtype: string
"""
if not self.is_absolute():
if origin is None or not origin.is_absolute():
raise NeedAbsoluteNameOrOrigin
labels = list(self.labels)
labels.extend(list(origin.labels))
else:
labels = self.labels
dlabels = [struct.pack('!B%ds' % len(x), len(x), x.lower())
for x in labels]
return b''.join(dlabels)
示例5: get_node
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def get_node(self, name, create=False):
"""Get a node in the zone, possibly creating it.
This method is like L{find_node}, except it returns None instead
of raising an exception if the node does not exist and creation
has not been requested.
@param name: the name of the node to find
@type name: dns.name.Name object or string
@param create: should the node be created if it doesn't exist?
@type create: bool
@rtype: dns.node.Node object or None
"""
try:
node = self.find_node(name, create)
except KeyError:
node = None
return node
示例6: get_uint32
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def get_uint32(self):
"""Read the next token and interpret it as a 32-bit unsigned
integer.
@raises dns.exception.SyntaxError:
@rtype: int
"""
token = self.get().unescape()
if not token.is_identifier():
raise dns.exception.SyntaxError('expecting an identifier')
if not token.value.isdigit():
raise dns.exception.SyntaxError('expecting an integer')
value = long(token.value)
if value < 0 or value > long(4294967296):
raise dns.exception.SyntaxError(
'%d is not an unsigned 32-bit integer' % value)
return value
示例7: _wait_for
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def _wait_for(fd, readable, writable, error, expiration):
done = False
while not done:
if expiration is None:
timeout = None
else:
timeout = expiration - time.time()
if timeout <= 0.0:
raise dns.exception.Timeout
try:
if not _polling_backend(fd, readable, writable, error, timeout):
raise dns.exception.Timeout
except select_error as e:
if e.args[0] != errno.EINTR:
raise e
done = True
示例8: to_digestable
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def to_digestable(self, origin=None):
"""Convert name to a format suitable for digesting in hashes.
The name is canonicalized and converted to uncompressed wire format.
@param origin: If the name is relative and origin is not None, then
origin will be appended to it.
@type origin: dns.name.Name object
@raises NeedAbsoluteNameOrOrigin: All names in wire format are
absolute. If self is a relative name, then an origin must be supplied;
if it is missing, then this exception is raised
@rtype: string
"""
if not self.is_absolute():
if origin is None or not origin.is_absolute():
raise NeedAbsoluteNameOrOrigin
labels = list(self.labels)
labels.extend(list(origin.labels))
else:
labels = self.labels
dlabels = ["%s%s" % (chr(len(x)), x.lower()) for x in labels]
return ''.join(dlabels)
示例9: get_uint32
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def get_uint32(self):
"""Read the next token and interpret it as a 32-bit unsigned
integer.
@raises dns.exception.SyntaxError:
@rtype: int
"""
token = self.get().unescape()
if not token.is_identifier():
raise dns.exception.SyntaxError('expecting an identifier')
if not token.value.isdigit():
raise dns.exception.SyntaxError('expecting an integer')
value = long(token.value)
if value < 0 or value > 4294967296L:
raise dns.exception.SyntaxError('%d is not an unsigned 32-bit integer' % value)
return value
示例10: _wait_for
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def _wait_for(fd, readable, writable, error, expiration):
done = False
while not done:
if expiration is None:
timeout = None
else:
timeout = expiration - time.time()
if timeout <= 0.0:
raise dns.exception.Timeout
try:
if not _polling_backend(fd, readable, writable, error, timeout):
raise dns.exception.Timeout
except select.error, e:
if e.args[0] != errno.EINTR:
raise e
done = True
示例11: _dns_query
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def _dns_query(self, qname, qtype):
# querys all system dns servers
# returns (answers, additional)
self.query_limit -= 1
if self.query_limit < 0:
raise SPFPermError('DNS query limit reached')
nameserver = dns.resolver.get_default_resolver().nameservers[0]
query = dns.message.make_query(qname, qtype)
# Only query first DNS server https://www.rfc-editor.org/rfc/rfc7208.txt (page 19 last paragraph)
self.logger.debug("resolving {0:<3} record for {1} using nameserver {2} (remaining queries: {3})".format(qtype, qname, nameserver, self.query_limit))
try:
response = dns.query.udp(query, nameserver, self.timeout)
except dns.exception.Timeout:
self.logger.warning("dns timeout reached, unable to query: {0} (type: {1}, nameserver: {2})".format(qname, qtype, nameserver))
raise SPFTimeOutError("DNS timeout reached, unable to query: {0} (type: {1}, nameserver: {2})".format(qname, qtype, nameserver))
except dns.exception.DNSException:
self.logger.warning("dns resolution error for: {0} (type: {1}, nameserver: {2})".format(qname, qtype, nameserver))
raise SPFTempError("DNS resolution error for: {0} (type: {1}, nameserver: {2})".format(qname, qtype, nameserver))
rcode = response.rcode()
# check for error codes per https://tools.ietf.org/html/rfc7208#section-5
if rcode not in (dns.rcode.NOERROR, dns.rcode.NXDOMAIN):
self.logger.warning("dns resolution error for: {0} (type: {1} rcode: {2})".format(qname, qtype, rcode))
raise SPFTempError("DNS resolution error for: {0} (type: {1} rcode: {2})".format(qname, qtype, rcode))
answers = []
if len(response.answer) == 0 or rcode == dns.rcode.NXDOMAIN:
self.logger.debug("resolving {0:<3} record for {1} using nameserver {2} resulted in a void lookup".format(qtype, qname, nameserver))
self.query_limit_void -= 1
if self.query_limit_void < 0:
raise SPFPermError('DNS query void lookup limit reached')
for answer in response.answer:
answers.extend(answer.items)
return answers, response.additional
示例12: test_do_afxr_fails_with_form_error
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def test_do_afxr_fails_with_form_error(self, mock_from_xfr, mock_xfr):
mock_from_xfr.side_effect = dns.exception.FormError()
masters = [
{'host': '192.168.0.1', 'port': 53},
]
self.assertRaises(
exceptions.XFRFailure,
dnsutils.do_axfr, 'example.com.', masters,
)
self.assertTrue(mock_xfr.called)
self.assertTrue(mock_from_xfr.called)
示例13: _send_dns_message
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def _send_dns_message(self, dns_message, dest_ip, dest_port, timeout):
try:
if not CONF['service:mdns'].all_tcp:
response = dns_query.udp(
dns_message, dest_ip, port=dest_port, timeout=timeout)
else:
response = dns_query.tcp(
dns_message, dest_ip, port=dest_port, timeout=timeout)
return response
except dns.exception.Timeout as timeout:
return timeout
except dns_query.BadResponse as badResponse:
return badResponse
示例14: test_dpi
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def test_dpi():
print("[O] Тестируем обход DPI" + (' (только IPv4)' if ipv6_available else ''))
dpiresults = []
for dpisite in sorted(dpi_list):
site = dpi_list[dpisite]
# First try to resolve IP address using Google API.
# Use a static one if this did not work.
newip = _get_a_record_over_google_api(site['host'])
if newip:
site['ip'] = newip[0]
if ipv6_available:
newip = _get_a_record_over_google_api(site['host'], 'AAAA')
if newip:
site['ipv6'] = newip[0]
dpi_built_tests = _dpi_build_tests(site['host'], site['urn'], site['ip'], site['lookfor'])
for testname in sorted(dpi_built_tests):
test = dpi_built_tests[testname]
print("\tПробуем способ «{}» на {}".format(testname, dpisite))
try:
result = _dpi_send(test.get('ip'), 80, test.get('data'), test.get('fragment_size'), test.get('fragment_count'))
except (KeyboardInterrupt, SystemExit) as e:
# re-raise exception to send it to caller function
raise e
except Exception as e:
print("[☠] Ошибка:", repr(e))
else:
if result.split("\n")[0].find('200 ') != -1 and result.find(test['lookfor']) != -1:
print("[✓] Сайт открывается")
dpiresults.append(testname)
elif result.split("\n")[0].find('200 ') == -1 and result.find(test['lookfor']) != -1:
print("[!] Сайт не открывается, обнаружен пассивный DPI!")
dpiresults.append('Passive DPI')
else:
print("[☠] Сайт не открывается")
return list(set(dpiresults))
示例15: get_dns_records
# 需要导入模块: import dns [as 别名]
# 或者: from dns import exception [as 别名]
def get_dns_records(domain, rdtype, nameserver):
"""Retrieves the DNS records matching the name and type and returns a list of records"""
records = []
try:
dns_resolver = dns.resolver.Resolver()
dns_resolver.nameservers = [nameserver]
dns_response = dns_resolver.query(domain, rdtype)
for rdata in dns_response:
for record in rdata.strings:
records.append(record.decode("utf-8"))
except dns.exception.DNSException:
sentry.captureException()
function = sys._getframe().f_code.co_name
metrics.send(f"{function}.fail", "counter", 1)
return records