Python dns.message() Examples

The following are 30 code examples of dns.message(). 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 , or try the search function .
Example #1
Source File: patator.py    From patator with GNU General Public License v2.0 9 votes vote down vote up
def execute(self, host, port='1521', user='', password='', sid='', service_name=''):

    if sid:
      dsn = cx_Oracle.makedsn(host=host, port=port, sid=sid)
    elif service_name:
      dsn = cx_Oracle.makedsn(host=host, port=port, service_name=service_name)
    else:
      raise ValueError('Options sid and service_name cannot be both empty')

    try:
      with Timing() as timing:
        fp = cx_Oracle.connect(user, password, dsn, threaded=True)

      code, mesg = '0', fp.version

    except cx_Oracle.DatabaseError as e:
      code, mesg = e.args[0].message[:-1].split(': ', 1)

    return self.Response(code, mesg, timing)

# }}}

# PostgreSQL {{{ 
Example #2
Source File: dns_proxy.py    From fdslight with GNU General Public License v2.0 6 votes vote down vote up
def request_dns(self, session_id, message):
        if len(message) < 16: return
        dns_id = (message[0] << 8) | message[1]
        n_dns_id = self.get_dns_id()
        if n_dns_id < 0: return

        self.set_dns_id_map(n_dns_id, (dns_id, session_id))
        L = list(message)
        L[0:2] = (
            (n_dns_id & 0xff00) >> 8,
            n_dns_id & 0x00ff
        )
        self.__timer.set_timeout(n_dns_id, self.__QUERY_TIMEOUT)

        self.send(bytes(L))
        self.add_evt_write(self.fileno) 
Example #3
Source File: mock_client.py    From deckard with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def sendto_msg(sock: socket.socket, message: bytes, addr: Optional[str] = None) -> None:
    """ Send DNS/UDP/TCP message. """
    try:
        if sock.type & socket.SOCK_DGRAM:
            if addr is None:
                sock.send(message)
            else:
                sock.sendto(message, addr)
        elif sock.type & socket.SOCK_STREAM:
            data = struct.pack("!H", len(message)) + message
            sock.sendall(data)
        else:
            raise NotImplementedError("[sendto_msg]: unknown socket type '%i'" % sock.type)
    except OSError as ex:
        # Reference: http://lkml.iu.edu/hypermail/linux/kernel/0002.3/0709.html
        if ex.errno != errno.ECONNREFUSED:
            raise 
Example #4
Source File: dnsrecon.py    From Yuki-Chan-The-Auto-Pentest with MIT License 6 votes vote down vote up
def query_ds(target, ns, timeout=5.0):
    """
    Function for performing DS Record queries. Returns answer object. Since a
    timeout will break the DS NSEC chain of a zone walk it will exit if a timeout
    happens.
    """
    try:
        query = dns.message.make_query(target, dns.rdatatype.DS, dns.rdataclass.IN)
        query.flags += dns.flags.CD
        query.use_edns(edns=True, payload=4096)
        query.want_dnssec(True)
        answer = dns.query.udp(query, ns, timeout)
    except dns.exception.Timeout:
        print_error("A timeout error occurred please make sure you can reach the target DNS Servers")
        print_error(
            "directly and requests are not being filtered. Increase the timeout from {0} second".format(timeout))
        print_error("to a higher number with --lifetime <time> option.")
        sys.exit(1)
    except:
        print("Unexpected error: {0}".format(sys.exc_info()[0]))
        raise
    return answer 
Example #5
Source File: mock_client.py    From deckard with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def sendto_msg(sock: socket.socket, message: bytes, addr: Optional[str] = None) -> None:
    """ Send DNS/UDP/TCP message. """
    try:
        if sock.type & socket.SOCK_DGRAM:
            if addr is None:
                sock.send(message)
            else:
                sock.sendto(message, addr)
        elif sock.type & socket.SOCK_STREAM:
            data = struct.pack("!H", len(message)) + message
            sock.sendall(data)
        else:
            raise NotImplementedError("[sendto_msg]: unknown socket type '%i'" % sock.type)
    except OSError as ex:
        # Reference: http://lkml.iu.edu/hypermail/linux/kernel/0002.3/0709.html
        if ex.errno != errno.ECONNREFUSED:
            raise 
Example #6
Source File: dnsrecon.py    From Yuki-Chan-The-Auto-Pentest with MIT License 6 votes vote down vote up
def check_recursive(ns_server, timeout):
    """
    Check if a NS Server is recursive.
    """
    is_recursive = False
    query = dns.message.make_query('www.google.com.', dns.rdatatype.NS)
    try:
        response = dns.query.udp(query, ns_server, timeout)
        recursion_flag_pattern = "\.*RA\.*"
        flags = dns.flags.to_text(response.flags)
        result = re.findall(recursion_flag_pattern, flags)
        if (result):
            print_error("\t Recursion enabled on NS Server {0}".format(ns_server))
        is_recursive = True
    except (socket.error, dns.exception.Timeout):
        return is_recursive
    return is_recursive 
Example #7
Source File: notify.py    From designate with Apache License 2.0 6 votes vote down vote up
def _send_dns_message(self, dns_message, host, port, timeout):
        """
        Send DNS Message over TCP or UDP, return response.

        :param dns_message: The dns message that needs to be sent.
        :param host: The destination ip of dns_message.
        :param port: The destination port of dns_message.
        :param timeout: The timeout in seconds to wait for a response.
        :return: response
        """
        send = dns_query.tcp if CONF['service:mdns'].all_tcp else dns_query.udp
        return send(
            dns_message,
            socket.gethostbyname(host),
            port=port,
            timeout=timeout
        ) 
Example #8
Source File: patator_ext.py    From project-black with GNU General Public License v2.0 6 votes vote down vote up
def execute(self, host, port='1521', user='', password='', sid='', service_name=''):

    if sid:
      dsn = cx_Oracle.makedsn(host=host, port=port, sid=sid)
    elif service_name:
      dsn = cx_Oracle.makedsn(host=host, port=port, service_name=service_name)
    else:
      raise ValueError('Options sid and service_name cannot be both empty')

    try:
      with Timing() as timing:
        fp = cx_Oracle.connect(user, password, dsn, threaded=True)

      code, mesg = '0', fp.version

    except cx_Oracle.DatabaseError as e:
      code, mesg = e.args[0].message[:-1].split(': ', 1)

    return self.Response(code, mesg, timing)

# }}}

# PostgreSQL {{{ 
Example #9
Source File: patator_ext.py    From project-black with GNU General Public License v2.0 6 votes vote down vote up
def format(self, record):
    if not record.msg or record.msg == 'headers':
      fmt = self.resultfmt

      if not all(True if 0x20 <= ord(c) < 0x7f else False for c in record.candidate):
        record.candidate = repr(record.candidate)

    else:
      if record.levelno == logging.DEBUG:
        fmt = '%(asctime)s %(name)-7s %(levelname)7s [%(pname)s] %(message)s'
      else:
        fmt = '%(asctime)s %(name)-7s %(levelname)7s - %(message)s'

    if PY3:
      self._style._fmt = fmt
    else:
      self._fmt = fmt

    return logging.Formatter.format(self, record) 
Example #10
Source File: https.py    From encrypted-dns with Apache License 2.0 6 votes vote down vote up
def query(self, dns_message):
        query_message = dns_message.to_wire()
        base64_query_string = self.struct_query(query_message)
        query_headers = {'Host': self._domain}
        query_parameters = {'dns': base64_query_string, 'ct': 'application/dns-message'}

        try:
            with requests.Session() as https_connection:
                https_connection.proxies = self._proxies
                response = https_connection.get(
                    "https://{}:{}/dns-query".format(self._ip, self._port),
                    params=query_parameters,
                    headers=query_headers
                )
                if response.status_code == requests.codes.ok:
                    return dns.message.from_wire(response.content)
                else:
                    response.raise_for_status()

        except socket.timeout:
            print('[Error] {}: socket timeout'.format(self._domain))
        except Exception:
            raise
        finally:
            https_connection.close() 
Example #11
Source File: test_notify.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_send_notify_message_non_auth(self):
        # id 10001
        # opcode NOTIFY
        # rcode NOTAUTH
        # flags QR
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        non_auth_notify_response = ("2711a4090001000000000000076578616d706c650"
                                    "3636f6d0000060001")
        context = self.get_context()
        with patch.object(dns.query, 'udp', return_value=dns.message.from_wire(
                binascii.a2b_hex(non_auth_notify_response))):
            response, retry = self.notify.notify_zone_changed(
                context, objects.Zone.from_dict(self.test_zone),
                self.nameserver.host, self.nameserver.port, 0, 0, 2, 0)
            self.assertIsNone(response)
            self.assertEqual(retry, 1) 
Example #12
Source File: test_notify.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_poll_for_serial_number(self):
        # id 10001
        # opcode QUERY
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # example.com. 3600 IN SOA example-ns.com. admin.example.com. 100 3600
        #  600 86400 3600
        # ;AUTHORITY
        # ;ADDITIONAL
        poll_response = ("271184000001000100000000076578616d706c6503636f6d0000"
                         "060001c00c0006000100000e1000290a6578616d706c652d6e73"
                         "c0140561646d696ec00c0000006400000e100000025800015180"
                         "00000e10")
        context = self.get_context()
        with patch.object(dns.query, 'udp', return_value=dns.message.from_wire(
                binascii.a2b_hex(poll_response))):
            status, serial, retries = self.notify.get_serial_number(
                context, objects.Zone.from_dict(self.test_zone),
                self.nameserver.host, self.nameserver.port, 0, 0, 2, 0)
            self.assertEqual(status, 'SUCCESS')
            self.assertEqual(serial, self.test_zone['serial'])
            self.assertEqual(retries, 2) 
Example #13
Source File: test_notify.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_poll_for_serial_number_higher_serial(self):
        # id 10001
        # opcode QUERY
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # example.com. 3600 IN SOA example-ns.com. admin.example.com. 101 3600
        #  600 86400 3600
        # ;AUTHORITY
        # ;ADDITIONAL
        poll_response = ("271184000001000100000000076578616d706c6503636f6d0000"
                         "060001c00c0006000100000e1000290a6578616d706c652d6e73"
                         "c0140561646d696ec00c0000006500000e100000025800015180"
                         "00000e10")
        context = self.get_context()
        with patch.object(dns.query, 'udp', return_value=dns.message.from_wire(
                binascii.a2b_hex(poll_response))):
            status, serial, retries = self.notify.get_serial_number(
                context, objects.Zone.from_dict(self.test_zone),
                self.nameserver.host, self.nameserver.port, 0, 0, 2, 0)
            self.assertEqual(status, 'SUCCESS')
            self.assertEqual(serial, 101)
            self.assertEqual(retries, 2) 
Example #14
Source File: check-slaves.py    From desec-stack with MIT License 6 votes vote down vote up
def report(self, outdated_slaves, output, timeouts):
        if not outdated_slaves and not timeouts:
            return

        subject = f'{timeouts and "CRITICAL ALERT" or "ALERT"} {len(outdated_slaves)} slaves out of sync'
        message = ''

        if timeouts:
            message += f'The following servers had timeouts:\n\n{timeouts}\n\n'

        if outdated_slaves:
            message += f'The following {len(outdated_slaves)} slaves are out of sync:\n'
            for outdated_slave in outdated_slaves:
                message += f'* {outdated_slave}\n'
            message += '\n'

        message += f'Current slave IPs: {self.servers}\n'
        message += '\n'.join(output)

        mail_admins(subject, message, connection=get_connection('django.core.mail.backends.smtp.EmailBackend')) 
Example #15
Source File: dns_proxy.py    From fdslight with GNU General Public License v2.0 6 votes vote down vote up
def udp_readable(self, message, address):
        size = len(message)
        if size < 16: return

        dns_id = (message[0] << 8) | message[1]
        if not self.dns_id_map_exists(dns_id): return
        n_dns_id, session_id = self.get_dns_id_map(dns_id)
        L = list(message)

        L[0:2] = (
            (n_dns_id & 0xff00) >> 8,
            n_dns_id & 0xff
        )
        self.del_dns_id_map(dns_id)
        self.__timer.drop(dns_id)

        self.dispatcher.response_dns(session_id, bytes(L)) 
Example #16
Source File: dnask.py    From cyber-security-framework with MIT License 6 votes vote down vote up
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 #17
Source File: dnask.py    From cyber-security-framework with MIT License 6 votes vote down vote up
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 #18
Source File: nsmap.py    From cyber-security-framework with MIT License 6 votes vote down vote up
def __init__(self):
        super().__init__()
        self.parser.add_argument("query", type=str, help="The query.")
        self.parser.add_argument("-t", "--timeout", type=int, default=8, help="The number of seconds to wait before the query times out.")
        self.parser.add_argument("-p", "--port", type=int, default=53, help="The port to which to send the message. The default is 53.")
        self.parser.add_argument("-i", "--ignore-unexpected", action="store_true", default=None, help="If True, ignore responses from unexpected.")
        self.parser.add_argument("-o", "--one-rr-per-rrset", action="store_true", default=None, help="Put each RR into its own RRset.")
        self.parser.add_argument("-e", "--use-edns", type=int, default=-1, help="The EDNS level to use. The default is -1 (no EDNS).")
        self.parser.add_argument("-s", "--want-dnssec", action="store_true", default=None, help="Should the query indicate that DNSSEC is desired?")
        self.parser.add_argument("-a", "--any", action="store_true", help = "Try executing an ANY metaquery.")
        
        self._nameservers = self.nameservers
        self.rdclasses = dict(sorted([(k, v) for k, v in dns.rdataclass.__dict__.items() if k.isupper()], key=lambda x: x[0]))
        self.rdtypes = dict(sorted([(k, v) for k, v in dns.rdatatype.__dict__.items() if k.isupper()], key=lambda x: x[0]))
        self._max_rdclass_length = max([len(rdclass) for rdclass in self.rdclasses])
        self._max_rdtype_length = max([len(rdtype) for rdtype in self.rdtypes]) 
Example #19
Source File: patator.py    From patator with GNU General Public License v2.0 6 votes vote down vote up
def format(self, record):
    if not record.msg or record.msg == 'headers':
      fmt = self.resultfmt

      if not all(True if 0x20 <= ord(c) < 0x7f else False for c in record.candidate):
        record.candidate = repr(record.candidate)

    else:
      if record.levelno == logging.DEBUG:
        fmt = '%(asctime)s %(name)-7s %(levelname)7s [%(pname)s] %(message)s'
      else:
        fmt = '%(asctime)s %(name)-7s %(levelname)7s - %(message)s'

    if PY3:
      self._style._fmt = fmt
    else:
      self._fmt = fmt

    return logging.Formatter.format(self, record) 
Example #20
Source File: core.py    From encrypted-dns with Apache License 2.0 6 votes vote down vote up
def firewall_clearance(self, wire_message, client_ip):
        try:
            dns_message = dns.message.from_wire(wire_message)
            if client_ip in self.firewall['client_blacklist']:
                return False

            if self.firewall['rate_limit'] > -1:
                self.rate_per_second[0] += 1
                if int(time.time()) - self.rate_per_second[1] >= 1:
                    self.rate_per_second = [0, int(time.time())]
                if self.firewall['rate_limit'] <= self.rate_per_second[0]:
                    return False

            if self.firewall['refuse_ANY']:
                for q in dns_message.question:
                    if q.rdtype == dns.rdatatype.ANY:
                        return False

            if self.firewall['disable_AAAA']:
                for q in dns_message.question:
                    if q.rdtype == dns.rdatatype.AAAA:
                        return False
            return True
        except Exception as exc:
            print("[Error]:", exc) 
Example #21
Source File: test_dnsutils.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_limit_notify_middleware(self):
        self.CONF.set_override('notify_delay', 0.1, 'service:agent')

        # Initialize the middlware
        placeholder_app = None
        middleware = dnsutils.LimitNotifyMiddleware(placeholder_app)

        # Prepare a NOTIFY
        zone_name = 'example.com.'
        notify = dns.message.make_query(zone_name, dns.rdatatype.SOA)
        notify.flags = 0
        notify.set_opcode(dns.opcode.NOTIFY)
        notify.flags |= dns.flags.AA

        # Send the NOTIFY through the middleware
        # No problem, middleware should return None to pass it on
        self.assertIsNone(middleware.process_request(notify)) 
Example #22
Source File: test_notify.py    From designate with Apache License 2.0 6 votes vote down vote up
def test_poll_for_serial_number_lower_serial(self):
        # id 10001
        # opcode QUERY
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. IN SOA
        # ;ANSWER
        # example.com. 3600 IN SOA example-ns.com. admin.example.com. 99 3600
        #  600 86400 3600
        # ;AUTHORITY
        # ;ADDITIONAL
        poll_response = ("271184000001000100000000076578616d706c6503636f6d0000"
                         "060001c00c0006000100000e1000290a6578616d706c652d6e73"
                         "c0140561646d696ec00c0000006300000e100000025800015180"
                         "00000e10")
        context = self.get_context()
        with patch.object(dns.query, 'udp', return_value=dns.message.from_wire(
                binascii.a2b_hex(poll_response))):
            status, serial, retries = self.notify.get_serial_number(
                context, objects.Zone.from_dict(self.test_zone),
                self.nameserver.host, self.nameserver.port, 0, 0, 2, 0)
            self.assertEqual(status, 'ERROR')
            self.assertEqual(serial, 99)
            self.assertEqual(retries, 0) 
Example #23
Source File: dns_proxy.py    From fdslight with GNU General Public License v2.0 5 votes vote down vote up
def message_from_handler(self, from_fd, message):
        self.__handle_msg_from_response(message) 
Example #24
Source File: dns_proxy.py    From fdslight with GNU General Public License v2.0 5 votes vote down vote up
def udp_readable(self, message, address):
        if self.__server_side:
            if self.__is_ipv6:
                byte_saddr = socket.inet_pton(socket.AF_INET6, address[0])
            else:
                byte_saddr = socket.inet_pton(socket.AF_INET, address[0])
            self.__handle_msg_for_request(byte_saddr, None, address[1], message, is_ipv6=self.__is_ipv6)
            return
        self.__handle_msg_from_response(message) 
Example #25
Source File: mock_client.py    From deckard with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def recvfrom_msg(sock: socket.socket,
                 timeout: int = SOCKET_OPERATION_TIMEOUT) -> Tuple[dns.message.Message, str]:
    data, addr = recvfrom_blob(sock, timeout=timeout)
    msg = dns.message.from_wire(data, one_rr_per_rrset=True)
    return msg, addr 
Example #26
Source File: mock_client.py    From deckard with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_dns_message(sock: socket.socket,
                    timeout: int = SOCKET_OPERATION_TIMEOUT) -> dns.message.Message:
    return dns.message.from_wire(get_answer(sock, timeout=timeout)) 
Example #27
Source File: dns_proxy.py    From fdslight with GNU General Public License v2.0 5 votes vote down vote up
def msg_from_tunnel(self, message):
        self.__handle_msg_from_response(message) 
Example #28
Source File: dns_proxy.py    From fdslight with GNU General Public License v2.0 5 votes vote down vote up
def dnsmsg_from_tun(self, saddr, daddr, sport, message, is_ipv6=False):
        self.__handle_msg_for_request(saddr, daddr, sport, message, is_ipv6=is_ipv6) 
Example #29
Source File: mock_client.py    From deckard with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def send_query(sock: socket.socket, query: Union[dns.message.Message, bytes]) -> None:
    message = query if isinstance(query, bytes) else query.to_wire()
    while True:
        try:
            sendto_msg(sock, message)
            break
        except OSError as ex:
            # ENOBUFS, throttle sending
            if ex.errno == errno.ENOBUFS:
                time.sleep(0.1)
            else:
                raise 
Example #30
Source File: check-slaves.py    From desec-stack with MIT License 5 votes vote down vote up
def query_serial(zone, server):
    """
    Checks a zone's serial on a server.
    :return: serial if received; None if the server did not know; False on error
    """
    query = dns.message.make_query(zone, 'SOA')
    try:
        response = dns.query.tcp(query, server, timeout=5)
    except dns.exception.Timeout:
        return False

    for rrset in response.answer:
        if rrset.rdtype == dns.rdatatype.SOA:
            return int(rrset[0].serial)
    return None