Python dns.resolver() Examples

The following are code examples for showing how to use dns.resolver(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: xn-twist   Author: xn-twist   File: xn_twist.py    (license) View Source Project 8 votes vote down vote up
def get_domain_dns(domain):
        """Get the DNS record, if any, for the given domain."""
        dns_records = list()

        try:
            # get the dns resolutions for this domain
            dns_results = dns.resolver.query(domain)
            dns_records = [ip.address for ip in dns_results]
        except dns.resolver.NXDOMAIN as e:
            # the domain does not exist so dns resolutions remain empty
            pass
        except dns.resolver.NoAnswer as e:
            # the resolver is not answering so dns resolutions remain empty
            pass

        return dns_records 
Example 2
Project: dkimpy   Author: oasiswork   File: dnsplug.py    (license) View Source Project 7 votes vote down vote up
def DNSLookup_dnspython(name,qtype,tcpfallback=True,timeout=30):
  retVal = []
  try:
    # FIXME: how to disable TCP fallback in dnspython if not tcpfallback?
    answers = dns.resolver.query(name, qtype)
    for rdata in answers:
      if qtype == 'A' or qtype == 'AAAA':
        retVal.append(((name, qtype), rdata.address))
      elif qtype == 'MX':
        retVal.append(((name, qtype), (rdata.preference, rdata.exchange)))
      elif qtype == 'PTR':
        retVal.append(((name, qtype), rdata.target.to_text(True)))
      elif qtype == 'TXT' or qtype == 'SPF':
        retVal.append(((name, qtype), rdata.strings))
  except dns.resolver.NoAnswer:
    pass
  except dns.resolver.NXDOMAIN:
    pass
  return retVal 
Example 3
Project: autoreg   Author: pbeyssac   File: check.py    (license) View Source Project 7 votes vote down vote up
def setnslist_public(self):
    """Fetch NS list from resolver"""
    tcp = False
    nslist = []
    try:
      ans = self.res.query(self.domain+'.', 'NS', tcp=tcp)
    except dns.resolver.NXDOMAIN:
      return None, _("Error: Domain not found")
    except dns.exception.Timeout:
      return None, _("Error: Timeout")
    except dns.resolver.NoAnswer:
      return None, _("Error: No answer")
    except dns.resolver.NoNameservers:
      return None, _("Error: No name servers")
    for i in ans.rrset.items:
      fqdn = i.to_text().upper()
      nslist.append(fqdn)
    self.setnslist_direct(nslist)
    return True, self.nslist 
Example 4
Project: fuel-plugin-dns-updater   Author: openstack   File: dns_lib.py    (license) View Source Project 6 votes vote down vote up
def lookup_hostname(name,dnsconf=DNS_CONF):
    try:
        resolv = dns.resolver.Resolver(configure=False)
        log.debug("initialize resolver")
        resolv.nameservers.append(dnsconf["nameserver"])
        resolv.domain = dns.name.from_text(dnsconf["domain"])
        resolv.search.append(dns.name.from_text(dnsconf["domain"]))
        log.debug("resolver {} {}".format(dnsconf["nameserver"],dnsconf["domain"]))
        try:
            answer = resolv.query(name)
            addr = answer.rrset[0]
            log.info("lookup host {} at {}".format(name, addr))
        except dns.exception.DNSException as e:#handle nxdomain - not an error
            log.info("instance not found: {}".format(repr(e)))
            addr = None
    except dns.exception.DNSException as e:
        log.error(repr(e))
        addr = None
    return addr 
Example 5
Project: fierce   Author: mschwager   File: test_fierce.py    (license) View Source Project 6 votes vote down vote up
def test_recursive_query_basic_failure(self):
        resolver = dns.resolver.Resolver()
        domain = dns.name.from_text('example.com.')
        record_type = 'NS'

        with unittest.mock.patch.object(fierce, 'query', return_value=None) as mock_method:
            result = fierce.recursive_query(resolver, domain, record_type=record_type)

        expected = [
            unittest.mock.call(resolver, 'example.com.', record_type),
            unittest.mock.call(resolver, 'com.', record_type),
            unittest.mock.call(resolver, '', record_type),
        ]

        mock_method.assert_has_calls(expected)
        self.assertIsNone(result) 
Example 6
Project: fierce   Author: mschwager   File: test_fierce.py    (license) View Source Project 6 votes vote down vote up
def test_recursive_query_long_domain_failure(self):
        resolver = dns.resolver.Resolver()
        domain = dns.name.from_text('sd1.sd2.example.com.')
        record_type = 'NS'

        with unittest.mock.patch.object(fierce, 'query', return_value=None) as mock_method:
            result = fierce.recursive_query(resolver, domain, record_type=record_type)

        expected = [
            unittest.mock.call(resolver, 'sd1.sd2.example.com.', record_type),
            unittest.mock.call(resolver, 'sd2.example.com.', record_type),
            unittest.mock.call(resolver, 'example.com.', record_type),
            unittest.mock.call(resolver, 'com.', record_type),
            unittest.mock.call(resolver, '', record_type),
        ]

        mock_method.assert_has_calls(expected)
        self.assertIsNone(result) 
Example 7
Project: fierce   Author: mschwager   File: test_fierce.py    (license) View Source Project 6 votes vote down vote up
def test_recursive_query_basic_success(self):
        resolver = dns.resolver.Resolver()
        domain = dns.name.from_text('example.com.')
        record_type = 'NS'
        good_response = unittest.mock.MagicMock()
        side_effect = [
            None,
            good_response,
            None,
        ]

        with unittest.mock.patch.object(fierce, 'query', side_effect=side_effect) as mock_method:
            result = fierce.recursive_query(resolver, domain, record_type=record_type)

        expected = [
            unittest.mock.call(resolver, 'example.com.', record_type),
            unittest.mock.call(resolver, 'com.', record_type),
        ]

        mock_method.assert_has_calls(expected)
        self.assertEqual(result, good_response) 
Example 8
Project: ldapdomaindump   Author: dirkjanm   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def lookupComputerDnsNames(self):
        dnsresolver = dns.resolver.Resolver()
        dnsresolver.lifetime = 2
        ipdef = attrDef.AttrDef('ipv4')
        if self.config.dnsserver != '':
            dnsresolver.nameservers = [self.config.dnsserver]
        for computer in self.computers:
            try:
                answers = dnsresolver.query(computer.dNSHostName.values[0], 'A')
                ip = str(answers.response.answer[0][0])
            except dns.resolver.NXDOMAIN:
                ip = 'error.NXDOMAIN'
            except dns.resolver.Timeout:
                ip = 'error.TIMEOUT'
            except (LDAPAttributeError, LDAPCursorError):
                ip = 'error.NOHOSTNAME'
            #Construct a custom attribute as workaround
            ipatt = attribute.Attribute(ipdef, computer, None)
            ipatt.__dict__['_response'] = ip
            ipatt.__dict__['raw_values'] = [ip]
            ipatt.__dict__['values'] = [ip]
            #Add the attribute to the entry's dictionary
            computer._state.attributes['IPv4'] = ipatt

    #Create a dictionary of all operating systems with the computer accounts that are associated 
Example 9
Project: DevOps   Author: YoLoveLife   File: dnstxt.py    (license) View Source Project 6 votes vote down vote up
def run(self, terms, variables=None, **kwargs):

        if HAVE_DNS == False:
            raise AnsibleError("Can't LOOKUP(dnstxt): module dns.resolver is not installed")

        ret = []
        for term in terms:
            domain = term.split()[0]
            string = []
            try:
                answers = dns.resolver.query(domain, 'TXT')
                for rdata in answers:
                    s = rdata.to_text()
                    string.append(s[1:-1])  # Strip outside quotes on TXT rdata

            except dns.resolver.NXDOMAIN:
                string = 'NXDOMAIN'
            except dns.resolver.Timeout:
                string = ''
            except DNSException as e:
                raise AnsibleError("dns.resolver unhandled exception", e)

            ret.append(''.join(string))

        return ret 
Example 10
Project: munch-core   Author: crunchmail   File: validators.py    (license) View Source Project 6 votes vote down vote up
def validate_no_virus(afile):
    """ Checks a file field against a remote antivirus service
    """
    if not settings.CAMPAIGNS['SKIP_VIRUS_CHECK']:
        try:
            host, port = settings.CLAMD_HOST, settings.CLAMD_PORT
        except AttributeError:
            results = dns.resolver.query(settings.CLAMD_SERVICE_NAME, 'SRV')
            servers = [(rr.target.to_text(True), rr.port) for rr in results]
            host, port = servers[0]

        cd = clamd.ClamdNetworkSocket(host=host, port=port)
        check_result, check_msg = cd.instream(afile)['stream']
        # example virus result
        # {'stream': ('FOUND', 'Eicar-Test-Signature')}
        if check_result == 'FOUND':
            raise ValidationError(_(
                'File contains virus: "{}"').format(check_msg))
    return afile 
Example 11
Project: openshift-event-controller   Author: redhat-cop   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def get_zone(dns_a_record, config, logger):
    resolv_conf = config.get('resolv_conf')
    if not resolv_conf:
        return None
 
    if os.path.exists(resolv_conf) == False:
        logger.warning("Specified resolv.conf does not exist. Please correct") 
    else:
        try:
            resolver = dns.resolver.Resolver(resolv_conf)
        except Exception as e:
            logger.error("Failed to create a valid Resolver. (error: {0})".format(e))

        dns_zone = dns.resolver.zone_for_name(dns_a_record, resolver=resolver)

    try:
        dns_zone
    except NameError:
        dns_zone = dns.resolver.zone_for_name(dns_a_record)

    return dns_zone 
Example 12
Project: ansible-provider-docs   Author: alibaba   File: dnstxt.py    (license) View Source Project 6 votes vote down vote up
def run(self, terms, variables=None, **kwargs):

        if HAVE_DNS is False:
            raise AnsibleError("Can't LOOKUP(dnstxt): module dns.resolver is not installed")

        ret = []
        for term in terms:
            domain = term.split()[0]
            string = []
            try:
                answers = dns.resolver.query(domain, 'TXT')
                for rdata in answers:
                    s = rdata.to_text()
                    string.append(s[1:-1])  # Strip outside quotes on TXT rdata

            except dns.resolver.NXDOMAIN:
                string = 'NXDOMAIN'
            except dns.resolver.Timeout:
                string = ''
            except DNSException as e:
                raise AnsibleError("dns.resolver unhandled exception %s" % to_native(e))

            ret.append(''.join(string))

        return ret 
Example 13
Project: PythonPool   Author: exp-db   File: domain_seeker.py    (license) View Source Project 6 votes vote down vote up
def run(self,thread_cnt=16):
        # ???????,check???????IP??
        all_queue,ok_queue = Queue.Queue(),Queue.Queue()
        for line in self.dict:
            all_queue.put('.'.join([str(line),str(self.target)]))
        
        e_ips,threads = self.resolver.extensive(self.target),[]
        # print '-- extensive',e_ips

        for i in xrange(thread_cnt):
            threads.append(self.bruteWorker(self.resolver,all_queue,ok_queue,e_ips))
        
        for t in threads: t.start()
        for t in threads: t.join()

        while not ok_queue.empty():
            yield ok_queue.get()

    # ??????? 
Example 14
Project: dmarc-tester   Author: usnistgov   File: clientcommons.py    (license) View Source Project 6 votes vote down vote up
def getdns(address, arnum):
  addparts = address.split('@')
  hashaddress = hashlib.sha224(addparts[0]).hexdigest()+'._openpgpkey.'+addparts[1]
  #try:
  rlist = dns.resolver.query(hashaddress, arnum)
  print "Rlist:"
  print rlist.rrset
  #except:
  #  print "Not found in DNS: %s" % (hashaddress)
  #  return False

  print "\nAddress:\n"+hashaddress
  for rdata in rlist:
    print "\nData:\n"+str(rdata)+"\n"
    try: something = base64.b64decode(str(rdata))
    except: 
      print "Corrupted data, won't import to gpg keys."
      return False
    stringtofile(something, tempgg)
  rkey = gippy['gpg_import_keys'](tempgg)
  return True



#Confirm that mykey is the one used to verify: 
Example 15
Project: dmarc-tester   Author: usnistgov   File: clientcommons.py    (license) View Source Project 6 votes vote down vote up
def import_key(myrecipient, fp, arnum):
    rkey = 0; body = ""
    try:
        addrparts = myrecipient.split('@')
        hashaddress = hashlib.sha224(addrparts[0]).hexdigest()+'._openpgpkey.'+addrparts[1]
        body = "The DNS query string we used to look up your public key is: \n%s\n" % (hashaddress)
        print "DNS query string from %s\nis: %s" % (myrecipient, hashaddress)
        rlist = dns.resolver.query(hashaddress, arnum)
        for rdata in rlist:
            last = str(rdata)
            something = base64.b64decode(str(rdata))
            print "rlist: \n%s\n" % (last)
        rkey = gippy['gpg_import_keys'](something)
        print "Key imported from DNS: %s" % (rkey)
        body += "Key imported from DNS: %s\n" % (rkey)
    except:
        print "Could not import key from DNS into keystore: %s" % (sys.exc_info()[0])
        body = body + "Could not import key from DNS into keystore: %s\n" % (sys.exc_info()[0])
        rkey = 0
    return (rkey, body)

#Store client key in keystore: 
Example 16
Project: ParadoxIP150v2   Author: Tertiush   File: client.py    (Eclipse Public License 1.0) View Source Project 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found.')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 17
Project: pentesting-multitool   Author: ffmancera   File: dns_utility.py    (license) View Source Project 5 votes vote down vote up
def run(self, domain, record, filename):

        if filename is not None:
            file = open(filename, 'a')
            print("File opened\n"
              "Writing the information on the file..")
            ans = dns.resolver.query(domain, record)
            file.write(ans.response.to_text())
            print("Done.")
            file.close()
        else:
            print('Getting information..')
            ans = dns.resolver.query(domain, record)
            print(ans.response.to_text()) 
Example 18
Project: AshsSDK   Author: thehappydinoa   File: client.py    (license) View Source Project 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found.')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FIXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 19
Project: fierce   Author: mschwager   File: test_fierce.py    (license) View Source Project 5 votes vote down vote up
def test_query_nxdomain(self):
        resolver = dns.resolver.Resolver()
        domain = dns.name.from_text('example.com.')

        with unittest.mock.patch.object(resolver, 'query', side_effect=dns.resolver.NXDOMAIN()):
            result = fierce.query(resolver, domain)

        self.assertIsNone(result) 
Example 20
Project: fierce   Author: mschwager   File: test_fierce.py    (license) View Source Project 5 votes vote down vote up
def test_query_no_nameservers(self):
        resolver = dns.resolver.Resolver()
        domain = dns.name.from_text('example.com.')

        with unittest.mock.patch.object(resolver, 'query', side_effect=dns.resolver.NoNameservers()):
            result = fierce.query(resolver, domain)

        self.assertIsNone(result) 
Example 21
Project: dbus-mqtt   Author: victronenergy   File: client.py    (license) View Source Project 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found.')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FIXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 22
Project: autoreg   Author: pbeyssac   File: check.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, domain, nslist=[], manualip={}, nat={}):
    self.res = dns.resolver.Resolver()
    self.domain = domain
    self.mastername = None
    self.manualip = manualip
    self.nat = nat
    qns = dns.message.make_query(domain+'.', 'NS')
    qns.flags = 0
    self.qns = qns
    if nslist:
      self.setnslist_direct(nslist)
      self.resolve_ips() 
Example 23
Project: autoreg   Author: pbeyssac   File: check.py    (license) View Source Project 5 votes vote down vote up
def gen_ips(self):
    """Resolve ips from self.nslist.
    Take manualip and nat tables into account.
    """
    tcp = False
    for fqdn in self.nslist:
      fqdn = fqdn.upper()
      if fqdn in self.manualip:
        yield True, (False, fqdn, self.manualip[fqdn])
        continue
      n = 0
      for t in ['A', 'AAAA']:
        try:
          aip = self.res.query(fqdn, t, tcp=tcp)
        except dns.resolver.NoAnswer:
          continue
        except dns.resolver.NXDOMAIN:
          continue
        except dns.exception.Timeout:
          continue
        except dns.resolver.NoNameservers:
          continue
        iplist = [ip.to_text() for ip in aip.rrset.items]
        natlist = []
        for ip in iplist:
          if ip in self.nat:
            natlist.append(self.nat[ip])
          else:
            natlist.append(ip)
        yield True, (True, fqdn, natlist)
        n += 1
      if n == 0:
        yield None, (None, fqdn, []) 
Example 24
Project: maltese   Author: HPE-AppliedSecurityResearch   File: utils.py    (license) View Source Project 5 votes vote down vote up
def get_default_dnsserver():
	default = dns.resolver.get_default_resolver()
	return default.nameservers[0] 
Example 25
Project: aws-iot-python   Author: vjammar   File: client.py    (license) View Source Project 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found.')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FIXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 26
Project: munch-core   Author: crunchmail   File: validators.py    (license) View Source Project 5 votes vote down vote up
def validate_existing_mail_domain(email):
    """ Just checks that the associated domain of an email has an MX record.
    """
    if settings.CAMPAIGNS['BYPASS_RECIPIENTS_MX_CHECK']:
        return
    domain = parseaddr(email)[1]

    if domain is None:
        # Trigger no error because email format is supposed to be checked
        # by another validator, needless to report it a second time
        return

    else:
        key = 'domcheck:{}'.format(domain)
        has_error = cache.get(key, None)

        if has_error is None:  # Not present in cache
            try:
                dns.resolver.query(domain, 'MX')
                has_error = False
            except dns.exception.DNSException:
                has_error = True
            finally:
                cache.set(key, has_error, 60)

        if has_error:
            raise ValidationError(_(
                'This domain "{}" doesn\'t seems to be '
                'configured to received emails').format(domain)) 
Example 27
Project: napalm-salt   Author: napalm-automation   File: netntp.py    (license) View Source Project 5 votes vote down vote up
def _check(peers):

    '''Checks whether the input is a valid list of peers and transforms domain names into IP Addresses'''

    if not isinstance(peers, list):
        return False

    for peer in peers:
        if not isinstance(peer, str):
            return False

    if not HAS_NETADDR:  # if does not have this lib installed, will simply try to load what user specified
        # if the addresses are not correctly specified, will trow error when loading the actual config
        return True

    ip_only_peers = []
    for peer in peers:
        try:
            ip_only_peers.append(str(IPAddress(peer)))  # append the str value
        except AddrFormatError:
            # if not a valid IP Address
            # will try to see if it is a nameserver and resolve it
            if not HAS_DNSRESOLVER:
                continue  # without the dns resolver cannot populate the list of NTP entities based on their nameserver
                # so we'll move on
            dns_reply = []
            try:
                # try to see if it is a valid NS
                dns_reply = dns.resolver.query(peer)
            except dns.resolver.NoAnswer:
                # no a valid DNS entry either
                return False
            for dns_ip in dns_reply:
                ip_only_peers.append(str(dns_ip))

    peers = ip_only_peers

    return True 
Example 28
Project: automatic-repo   Author: WZQ1397   File: dnsresolver.py    (license) View Source Project 5 votes vote down vote up
def get_iplist(domain=""):       #???????????IP?????iplist
    try:
        A = dns.resolver.query(domain, 'A')  #??A????
    except Exception as e:
        print("dns resolver error:"+str(e))
        return
    for i in A.response.answer:
        for j in i.items:
            iplist.append(j)   #???Iplist
    return True 
Example 29
Project: python   Author: emitter-io   File: paho.py    (license) View Source Project 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found, try "pip install dnspython" or "pip3 install dnspython3".')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FIXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 30
Project: pizza-auth   Author: xxpizzaxx   File: announce.py    (license) View Source Project 5 votes vote down vote up
def sendannounce(self, server, message):
		tojid = server+"/announce/online"
		jidparams={}
		jidparams['jid'] = self.username+"@"+server
		jidparams['password'] = self.passwd

		jid=xmpp.protocol.JID(jidparams['jid'])

		try:
			r = dns.resolver.query('_xmpp-client._tcp.%s' % server, dns.rdatatype.SRV)
			if len(r)==1:
				server = r[0].target.to_text().rstrip(".")
		except:
			pass

		cl=xmpp.Client(server, debug=[])

		con=cl.connect()
		if not con:
		    print 'could not connect!'
		    sys.exit()
		print 'connected with',con
		auth=cl.auth(jid.getNode(),jidparams['password'],resource=jid.getResource())
		if not auth:
		    print 'could not authenticate!'
		    sys.exit()
		print 'authenticated using',auth

		id=cl.send(xmpp.protocol.Message(tojid,message))
		print 'sent message with id',id 
Example 31
Project: cloudcam   Author: revmischa   File: client.py    (license) View Source Project 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found.')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FIXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 32
Project: sdk-samples   Author: cradlepoint   File: client.py    (license) View Source Project 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found, try "pip install dnspython" or "pip3 install dnspython3".')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FIXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 33
Project: HomeWizard-   Author: bramkelder   File: client.py    (license) View Source Project 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found.')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FIXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 34
Project: opendxl-client-python   Author: opendxl   File: client.py    (license) View Source Project 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found.')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FIXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 35
Project: maas   Author: maas   File: test_config.py    (license) View Source Project 5 votes vote down vote up
def setUp(self):
        super(TestDNSServer, self).setUp()
        # Ensure there's an initial DNS publication. Outside of tests this is
        # guaranteed by a migration.
        DNSPublication(source="Initial").save()
        # Allow test-local changes to configuration.
        self.useFixture(RegionConfigurationFixture())
        # Immediately make DNS changes as they're needed.
        self.patch(dns_config_module, "DNS_DEFER_UPDATES", False)
        # Create a DNS server.
        self.bind = self.useFixture(BINDServer())
        # Use the dnspython resolver for at least some queries.
        self.resolver = dns.resolver.Resolver()
        self.resolver.nameservers = ['127.0.0.1']
        self.resolver.port = self.bind.config.port
        patch_dns_config_path(self, self.bind.config.homedir)
        # Use a random port for rndc.
        patch_dns_rndc_port(self, allocate_ports("localhost")[0])
        # This simulates what should happen when the package is
        # installed:
        # Create MAAS-specific DNS configuration files.
        call_command('set_up_dns')
        # Register MAAS-specific DNS configuration files with the
        # system's BIND instance.
        call_command(
            'get_named_conf', edit=True,
            config_path=self.bind.config.conf_file)
        # Reload BIND.
        self.bind.runner.rndc('reload') 
Example 36
Project: PythonPool   Author: exp-db   File: domain_seeker.py    (license) View Source Project 5 votes vote down vote up
def __init__(self,nameservers=[],timeout=''):
        self.resolver = dns.resolver.Resolver()
        if nameservers: self.resolver.nameservers = nameservers
        if timeout: self.resolver.timeout = timeout
        

    # ??????IP?? 
Example 37
Project: PythonPool   Author: exp-db   File: domain_seeker.py    (license) View Source Project 5 votes vote down vote up
def query(self,target,rdtype):
        try:
            answer = self.resolver.query(target, rdtype)
            return self.parser(answer)
        except dns.resolver.NoAnswer:
            return None # catch the except, nothing to do
        except dns.resolver.NXDOMAIN:
            return None # catch the except, nothing to do
        except dns.resolver.Timeout:
            # timeout retry
            print(target, rdtype, '<timeout>')
        except Exception, e:
            raise e
            logging.info(str(e)) 
Example 38
Project: PythonPool   Author: exp-db   File: domain_seeker.py    (license) View Source Project 5 votes vote down vote up
def __init__(self,target,dict_file='top200_domain.txt'):
        self.target = target
        self.dict = list(set(FileUtils.getLines(dict_file)))
        self.resolver = Domain(NAMESERVERS,timeout=5)

    # ????? ?? 
Example 39
Project: PythonPool   Author: exp-db   File: domain_seeker.py    (license) View Source Project 5 votes vote down vote up
def __init__(self,resolver,all_queue,ok_queue,extensive=[]):
            threading.Thread.__init__(self)
            self.all_queue = all_queue
            self.resolver = resolver
            self.ok_queue = ok_queue
            self.extensive = extensive 
Example 40
Project: aws-iot-device-sdk-python   Author: aws   File: client.py    (license) View Source Project 5 votes vote down vote up
def connect_srv(self, domain=None, keepalive=60, bind_address=""):
        """Connect to a remote broker.

        domain is the DNS domain to search for SRV records; if None,
        try to determine local domain name.
        keepalive and bind_address are as for connect()
        """

        if HAVE_DNS is False:
            raise ValueError('No DNS resolver library found.')

        if domain is None:
            domain = socket.getfqdn()
            domain = domain[domain.find('.') + 1:]

        try:
            rr = '_mqtt._tcp.%s' % domain
            if self._ssl is not None:
                # IANA specifies secure-mqtt (not mqtts) for port 8883
                rr = '_secure-mqtt._tcp.%s' % domain
            answers = []
            for answer in dns.resolver.query(rr, dns.rdatatype.SRV):
                addr = answer.target.to_text()[:-1]
                answers.append((addr, answer.port, answer.priority, answer.weight))
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
            raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain))

        # FIXME: doesn't account for weight
        for answer in answers:
            host, port, prio, weight = answer

            try:
                return self.connect(host, port, keepalive, bind_address)
            except:
                pass

        raise ValueError("No SRV hosts responded") 
Example 41
Project: LinuxBashShellScriptForOps   Author: DingGuodong   File: dnsHttpHealthCheck.py    (license) View Source Project 5 votes vote down vote up
def get_ip_address_list(domain=""):
    try:
        record_a = dns.resolver.query(domain, 'A')  # A recode type
    except Exception, e:
        print "dns resolver error:" + str(e)
        return
    for i in record_a.response.answer:
        for j in i.items:
            ip_addressList.append(j.address)  # append to ip_addressList
    return True 
Example 42
Project: lib9   Author: Jumpscale   File: DNSTools.py    (license) View Source Project 5 votes vote down vote up
def getNameserversForDomain(self,domain="threefoldtoken.org",nameserver="8.8.8.8"):

        resolver = dns.resolver.Resolver(configure=False)
        resolver.nameservers = [nameserver]
        answer = dns.resolver.query(domain, 'NS')

        res=[]
        for rr in answer:
            res.append( rr.target.to_text())
        return res 
Example 43
Project: lib9   Author: Jumpscale   File: DNSTools.py    (license) View Source Project 5 votes vote down vote up
def getNameRecordIPs(self,dnsurl="www.threefoldtoken.org",nameserver="8.8.8.8"):
        """
        return ip addr for a full name
        """

        resolver = dns.resolver.Resolver(configure=False)
        resolver.nameservers = [nameserver]
        answer = dns.resolver.query(dnsurl, 'A')

        res=[]
        for rr in answer:
            res.append( rr.address)
        return res 
Example 44
Project: maas   Author: maas   File: test_config.py    (license) View Source Project 4 votes vote down vote up
def dns_wait_soa(self, fqdn, removing=False):
        # Get the serial number for the zone containing the FQDN by asking DNS
        # nicely for the SOA for the FQDN.  If it's top-of-zone, we get an
        # answer, if it's not, we get the SOA in authority.

        if not fqdn.endswith('.'):
            fqdn = fqdn + '.'

        for elapsed, remaining, wait in retries(15, 0.02):
            query_name = fqdn

            # Loop until we have a value for serial, be that numeric or None.
            serial = undefined = object()
            while serial is undefined:
                try:
                    ans = self.resolver.query(
                        query_name, 'SOA', raise_on_no_answer=False)
                except dns.resolver.NXDOMAIN:
                    if removing:
                        # The zone has gone; we're done.
                        return
                    elif "." in query_name:
                        # Query the parent domain for the SOA record.
                        # For most things, this will be the correct DNS zone.
                        # In the case of SRV records, we'll actually need to
                        # strip more, hence the loop.
                        query_name = query_name.split('.', 1)[1]
                    else:
                        # We've hit the root zone; no SOA found.
                        serial = None
                except dns.resolver.NoNameservers:
                    # No DNS service as yet.
                    serial = None
                else:
                    # If we got here, then we either have (1) a situation where
                    # the LHS exists in the DNS, but no SOA RR exists for that
                    # LHS (because it's a node with an A or AAAA RR, and not
                    # the domain...) or (2) an answer to our SOA query.
                    # Either way, we get exactly one SOA in the reply: in the
                    # first case, it's in the Authority section, in the second,
                    # it's in the Answer section.
                    if ans.rrset is None:
                        serial = ans.response.authority[0].items[0].serial
                    else:
                        serial = ans.rrset.items[0].serial

            if serial == DNSPublication.objects.get_most_recent().serial:
                # The zone is up-to-date; we're done.
                return
            else:
                time.sleep(wait)

        self.fail("Timed-out waiting for %s to update." % fqdn)