def record_judge(query):
    try:
        DNS.DiscoverNameServers()
        reqobj = DNS.Request()
        answerobj_a = reqobj.req(name=query,
                                 qtype=DNS.Type.A,
                                 server="222.194.15.253")
        if len(answerobj_a.answers):
            return 1
        else:
            pass
    except:
        pass
    try:
        DNS.DiscoverNameServers()
        reqobj = DNS.Request()
        answerobj_a = reqobj.req(name=query,
                                 qtype=DNS.Type.MX,
                                 server="222.194.15.253")
        if len(answerobj_a.answers):
            return 1
        else:
            pass
    except:
        pass
    return 0
Exemple #2
0
    def clean(self, value):
        """ Make sure the e-mail address is sane """
        email = super(ValidHostEmailField, self).clean(value)
        email_parts = email.split("@")
        if len(email_parts) != 2:
            raise forms.ValidationError(
                'E-mail addresses must be of the form "name@host"')

        email_host = email_parts[1].encode('ascii')

        try:
            import DNS
            try:
                DNS.DiscoverNameServers()
                if len(DNS.Request(
                        qtype='a').req(email_host).answers) == 0 and len(
                            DNS.Request(
                                qtype='mx').req(email_host).answers) == 0:
                    raise forms.ValidationError(
                        '"%s" is not a valid e-mail host' % email_host)
            except (IOError, DNS.DNSError):  # (no resolv.conf, no nameservers)
                pass
        except ImportError:  # no PyDNS
            pass

        return email
Exemple #3
0
 def lookup_dns(self, domain):
     if not self.discoverNS:
         DNS.DiscoverNameServers()
         self.discoverNS = True
     name = '_dmarc.' + domain
     try:
         req = DNS.DnsRequest(name=name,
                              qtype=DNS.Type.TXT,
                              timeout=self.dnstimeout)
         res = req.req()
         if res.header['tc'] == True:
             try:
                 req = DNS.DnsRequest(name,
                                      qtype='TXT',
                                      protocol='tcp',
                                      timeout=self.dnstimeout)
                 res = req.req()
             except DNS.DNSError as x:
                 print('DNS: TCP fallback error:', str(x))
             if res.header['rcode'] != 0 and res.header['rcode'] != 3:
                 print('DNS Error:', res.header['status'],
                       ' RCODE ({})'.format(res.header['rcode']))
         return [((a['name'], a['typename']), a['data'])
                 for a in res.answers] \
                     + [((a['name'], a['typename']), a['data'])
                        for a in res.additional]
     except AttributeError as x:
         print('DNS attribute:' + str(x))
     except IOError as x:
         print('DNS IOE:' + str(x))
     except DNS.DNSError as x:
         'DNS ' + str(x)
    def srv_lookup(self, server):
        " SRV resolver. Takes server=(host, port) as argument. Returns new (host, port) pair "
        if HAVE_DNSPYTHON or HAVE_PYDNS:
            host, port = server
            possible_queries = ['_xmpp-client._tcp.' + host]

            for query in possible_queries:
                try:
                    if HAVE_DNSPYTHON:
                        answers = [x for x in dns.resolver.query(query, 'SRV')]
                        if answers:
                            host = str(answers[0].target)
                            port = int(answers[0].port)
                            break
                    elif HAVE_PYDNS:
                        # ensure we haven't cached an old configuration
                        DNS.DiscoverNameServers()
                        response = DNS.Request().req(query, qtype='SRV')
                        answers = response.answers
                        if len(answers) > 0:
                            # ignore the priority and weight for now
                            _, _, port, host = answers[0]['data']
                            del _
                            port = int(port)
                            break
                except:
                    self.DEBUG('An error occurred while looking up %s' % query,
                               'warn')
            server = (host, port)
        else:
            self.DEBUG(
                "Could not load one of the supported DNS libraries (dnspython or pydns). SRV records will not be queried and you may need to set custom hostname/port for some servers to be accessible.\n",
                'warn')
        # end of SRV resolver
        return server
Exemple #5
0
    def __init__(self, cloud_prop):
        if MISSING_LIBS:
            raise CloudError("missing libraries required by libvirt deployment: %s" % (", ".join(MISSING_LIBS)))

        Provider.__init__(self, 'libvirt', cloud_prop)
        self.log = logging.getLogger("poni.libvirt")
        self.ssh_key = None
        profile = json.load(open(cloud_prop["profile"], "rb"))
        if "ssh_key" in profile:
            self.ssh_key = os.path.expandvars(os.path.expanduser(profile["ssh_key"]))

        # Look up all hypervisor hosts, they can be defined one-by-one
        # ("nodes" property) in which case we use the highest priorities
        # with them.  They can also be defined in SRV records in "services"
        # property as well as an older style "nodesets" property without
        # service information in which case we use _libvirt._tcp.
        if not DNS.defaults["server"]:
            DNS.DiscoverNameServers()
        hosts = {}
        for entry in profile.get("nodes", []):
            host, _, port = entry.partition(":")
            hosts["{0}:{1}".format(host, port or 22)] = (0, 100)
        services = set(profile.get("services", []))
        services.update("_libvirt._tcp.{0}".format(host) for host in profile.get("nodesets", []))
        for entry in services:
            for priority, weight, port, host in _lv_dns_lookup(entry, "SRV"):
                hosts["{0}:{1}".format(host, port)] = (priority, weight)
        self.hosts = hosts
        self.hosts_online = None
Exemple #6
0
def lookup_ip_address(hostname, ipv6):
    """
    Try to get IPv4 or IPv6 addresses for the given hostname
    """

    DNS.DiscoverNameServers()
    try:
        if ipv6:
            dns_request = DNS.Request(name=hostname, qtype=DNS.Type.AAAA).req()
        else:
            dns_request = DNS.Request(name=hostname, qtype=DNS.Type.A).req()
    except DNS.DNSError as message:
        print("DNS Error: %s (%s)" % (message, hostname))
        return None

    if dns_request.header['status'] != 'NOERROR':
        print("DNS Error: status=%s (%s)" %
              (dns_request.header['status'], hostname))
        return None

    for answer in dns_request.answers:
        if ('data' not in answer) or (not answer['data']):
            continue
        if (ipv6 and answer['typename'] != 'AAAA') or (
                not ipv6 and answer['typename'] != 'A'):
            continue  # skip CNAME records

        if ipv6:
            return inet_ntop(AF_INET6, answer['data'])
        else:
            return answer['data']

    return None
Exemple #7
0
def validate_email(email, check_mx=False, verify=False):
    try:
        check_mx |= verify
        if check_mx:
            if not DNS:
                raise Exception(
                    'For check the mx records or check if the email exists you must have installed pyDNS python package'
                )
            DNS.DiscoverNameServers()
            hostname = email[email.find('@') + 1:]
            mx_hosts = DNS.mxlookup(hostname)
            for mx in mx_hosts:
                print("mx:", mx)
                try:
                    smtp = smtplib.SMTP()
                    smtp.connect(mx[1])
                    if not verify: return True
                    status, _ = smtp.helo()
                    if status != 250: continue
                    smtp.mail('')
                    status, _ = smtp.rcpt(email)
                    if status != 250: return False
                    break
                except smtplib.SMTPServerDisconnected:  #Server not permits verify user
                    break
                except smtplib.SMTPConnectError:
                    continue
    except (AssertionError, ServerError):
        return False
    return True
def validate_email(email, check_mx=False, verify=False, debug=False):
    """Indicate whether the given string is a valid email address
    according to the 'addr-spec' portion of RFC 2822 (see section
    3.4.1).  Parts of the spec that are marked obsolete are *not*
    included in this test, and certain arcane constructions that
    depend on circular definitions in the spec may not pass, but in
    general this should correctly identify any email address likely
    to be in use as of 2011."""
    if debug:
        logger = logging.getLogger('validate_email')
        logger.setLevel(logging.DEBUG)
    else:
        logger = None

    try:
        assert re.match(VALID_ADDRESS_REGEXP, email) is not None
        check_mx |= verify
        if check_mx:
            if not DNS:
                raise Exception('For check the mx records or check if the email exists you must '
                                'have installed pyDNS python package')
            DNS.DiscoverNameServers()
            hostname = email[email.find('@') + 1:]
            mx_hosts = get_mx_ip(hostname)
            for mx in mx_hosts:
                try:
                    smtp = smtplib.SMTP()
                    smtp.connect(mx[1])
                    if not verify:
                        smtp.quit()
                        return True
                    status, _ = smtp.helo()
                    if status != 250:
                        smtp.quit()
                        if debug:
                            logger.debug(u'%s answer: %s - %s', mx[1], status, _)
                        continue
                    smtp.mail('')
                    status, _ = smtp.rcpt(email)
                    if status == 250:
                        smtp.quit()
                        return True
                    if debug:
                        logger.debug(u'%s answer: %s - %s', mx[1], status, _)
                    smtp.quit()
                except smtplib.SMTPServerDisconnected:  # Server not permits verify user
                    if debug:
                        logger.debug(u'%s disconected.', mx[1])
                except smtplib.SMTPConnectError:
                    if debug:
                        logger.debug(u'Unable to connect to %s.', mx[1])
            return None
    except AssertionError:
        return False
    except (ServerError, socket.error) as e:
        if debug:
            logger.debug('ServerError or socket.error exception raised (%s).', e)
        return None
    return True
Exemple #9
0
def dnsrequest(domain):
    """dnsrequest(domain)"""
    import DNS
    DNS.DiscoverNameServers()
    r = DNS.Request()
    res = r.req(name=domain, qtype=255)
    for i in res.answers:
        print('%-5s %s' % (i['typename'], i['data']))
    if not res.answers: print('Domain not found')
Exemple #10
0
def lookup_avatar_server(domain, https):
    """
    Extract the avatar server from an SRV record in the DNS zone

    The SRV records should look like this:

       _avatars._tcp.example.com.     IN SRV 0 0 80  avatars.example.com
       _avatars-sec._tcp.example.com. IN SRV 0 0 443 avatars.example.com
    """

    if domain and len(domain) > 60:
        domain = domain[:60]

    service_name = None
    if https:
        service_name = "_avatars-sec._tcp.%s" % domain
    else:
        service_name = "_avatars._tcp.%s" % domain

    DNS.DiscoverNameServers()
    try:
        dns_request = DNS.Request(name=service_name, qtype='SRV').req()
    except DNS.DNSError as message:
        print "DNS Error: %s (%s)" % (message, domain)
        return None

    if 'NXDOMAIN' == dns_request.header['status']:
        # Not an error, but no point in going any further
        return None

    if dns_request.header['status'] != 'NOERROR':
        print "DNS Error: status=%s (%s)" % (dns_request.header['status'],
                                             domain)
        return None

    records = []
    for answer in dns_request.answers:
        if ('data' not in answer) or (not answer['data']) or (
                not answer['typename']) or (answer['typename'] != 'SRV'):
            continue

        rr = {
            'priority': int(answer['data'][0]),
            'weight': int(answer['data'][1]),
            'port': int(answer['data'][2]),
            'target': answer['data'][3]
        }

        records.append(rr)

    target, port = srv_hostname(records)

    if target and ((https and port != 443) or (not https and port != 80)):
        return "%s:%s" % (target, port)

    return target
Exemple #11
0
    def __init__(self, dnsServer=None, cachefile=""):
        # These attributes intended for user setting
        self.printStatsAtEnd = False

        # As far as I can tell from the standards,
        # it's legal to have more than one PTR record
        # for an address. That is, it's legal to get
        # more than one name back when you do a
        # reverse lookup on an IP address. I don't
        # know of a use for that and I've never seen
        # it done. And I don't think that most
        # people would expect it. So forward ("A")
        # lookups always return a list. Reverse
        # ("PTR") lookups return a single name unless
        # this attribute is set to False.
        self.returnSinglePTR = True

        # How long to cache an error as no data
        self.cacheErrorSecs = 5 * 60

        # How long to wait for the server
        self.dnsTimeout = 10

        # end of user-settable attributes

        self.cachefile = os.path.expanduser(cachefile)
        self.caches = None

        if self.cachefile and os.path.exists(self.cachefile):
            try:
                self.caches = pickle_read(self.cachefile)
            except:
                os.unlink(self.cachefile)

        if self.caches is None:
            self.caches = {"A": {}, "PTR": {}}

        if options["globals", "verbose"]:
            if self.caches["A"] or self.caches["PTR"]:
                print >> sys.stderr, "opened existing cache with",
                print >> sys.stderr, len(self.caches["A"]), "A records",
                print >> sys.stderr, "and", len(self.caches["PTR"]),
                print >> sys.stderr, "PTR records"
            else:
                print >> sys.stderr, "opened new cache"

        self.hits = 0  # These two for statistics
        self.misses = 0
        self.pruneTicker = 0

        if dnsServer == None:
            DNS.DiscoverNameServers()
            self.queryObj = DNS.DnsRequest()
        else:
            self.queryObj = DNS.DnsRequest(server=dnsServer)
        return None
Exemple #12
0
def FindCNAME(domain):
    DNS.DiscoverNameServers()
    reqobj = DNS.Request()
    try:
        print domain
        answerobj = reqobj.req(domain)  #这句
        x = answerobj.answers
    except Exception,e:
        print e
        return  "none"
Exemple #13
0
def check_srv(domain):
    """ takes a domain and finds minecraft SRV records """
    DNS.DiscoverNameServers()
    srv_req = DNS.Request(qtype='srv')
    srv_result = srv_req.req('_minecraft._tcp.{}'.format(domain))

    for getsrv in srv_result.answers:
        if getsrv['typename'] == 'SRV':
            data = [getsrv['data'][2], getsrv['data'][3]]
            return data
Exemple #14
0
def get_dbservername(domainname):
	'''Datenbankserver ermitteln'''
	log('get dbservername for ' + domainname)
	DNS.DiscoverNameServers()
	dbsrvname = None
	try:
		dbsrvname = map(lambda x: x['data'], DNS.DnsRequest('_pkgdb._tcp.' + domainname, qtype='srv').req().answers)[0][3]
	except:
		log('Cannot find service-record of _pkgdb._tcp.')
		print('Cannot find service-record of _pkgdb._tcp.')
	return dbsrvname
Exemple #15
0
def quick_mx_lookup(email):
    DNS.DiscoverNameServers()
    hostname = email[email.find('@') + 1:]

    try:
        mx_hosts = DNS.mxlookup(hostname)
    except:
        return False

    if len(mx_hosts) != 0:
        return True
    else:
        return False
Exemple #16
0
def is_using_tor(client_ip, el_port='80'):
    '''
    Find out if clientIp is a tor exit node following query type one.
    Inspired by https://svn.torproject.org/svn/check/trunk/cgi-bin/TorCheck.py
    Query Specification under https://gitweb.torproject.org/tordnsel.git/blob/HEAD:/doc/torel-design.txt
    See also https://check.torproject.org/
    '''

    DNS.DiscoverNameServers()

    # Put user ip in right format
    split_ip = client_ip.split('.')
    split_ip.reverse()
    el_exit_node = '.'.join(split_ip)

    # get beam's current ip address
    name = settings.ENV_SITE_MAPPING[settings.ENV][settings.SITE_USER]
    el_target = DNS.dnslookup(name, 'A')

    # ExitList DNS server we want to query
    el_host = 'ip-port.exitlist.torproject.org'

    # Prepare the question as an A record (i.e. a 32-bit IPv4 address) request
    el_question = el_exit_node + "." + el_port + "." + el_target[
        1] + "." + el_host
    request = DNS.DnsRequest(name=el_question,
                             qtype='A',
                             timeout=settings.TOR_TIMEOUT)

    # Ask the question and load the data into our answer
    try:
        answer = request.req()
    except DNS.DNSError as e:
        log_error('ERROR Tor - Failed to query ip address: {}'.format(e[0]))
        return False

    # Parse the answer and decide if it's allowing exits
    # 127.0.0.2 is an exit and NXDOMAIN is not
    if answer.header['status'] == 'NXDOMAIN':
        return False
    else:
        # unexpected response
        if not answer.answers:
            log_error('ERROR Tor - Query returned unexpected response')
            return False
        for a in answer.answers:
            if a['data'] != '127.0.0.2':
                return False
        return True
Exemple #17
0
    def _get_mx1(self, domain):
        if domain in ('localhost', ):
            return None

        import DNS
        # FIXME: This bypasses the connection broker and is not secured or
        #        anonymized.
        DNS.DiscoverNameServers()
        try:
            timeout = (self.deadline - time.time()) // 2
            mxlist = DNS.DnsRequest(name=domain,
                                    qtype=DNS.Type.MX,
                                    timeout=timeout).req()
            mxs = sorted([m['data'] for m in mxlist.answers if 'data' in m])
            return mxs[0][1] if mxs else None
        except socket.error:
            return None
Exemple #18
0
def get_nameservers():
    try:
        import DNS
    except ImportError:
        raise Exception(
            'You must have the PyDNS package installed to fetch the nameserver config'
        )

    nameservers = DNS.defaults.get('server', None)

    if not nameservers:
        logger.info('discovering nameservers ...')
        DNS.DiscoverNameServers()
        nameservers = DNS.defaults.get('server', None)

    logger.info('nameservers: %s' % nameservers)
    return nameservers
def checkmail(mail, attempts=0):
    DNS.DiscoverNameServers()
    hostname = mail[mail.find('@') + 1:]
    try:
        mx_hosts = DNS.mxlookup(hostname)
    except:
        print 'failed email', mail
        return False
    # except:
    #     if attempts > 5:
    #         print 'Timeout'
    #     else:
    #         print 'failed email', mail
    #         attempts += 1
    #         time.sleep(5)
    #         checkmail(mail, attempts)
    failed_mx = True
    for mx in mx_hosts:
        smtp = smtplib.SMTP()
        try:
            smtp.connect(mx[1])
            failed_mx = False
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((mx[1], 25))
            s.recv(1024)
            s.send("HELO %s\n" % (mx[1]))
            s.recv(1024)
            s.send("MAIL FROM:< *****@*****.**>\n")
            s.recv(1024)
            s.send("RCPT TO:<%s>\n" % (mail))
            result = s.recv(1024)
            if result.find('Recipient address rejected') > 0:
                failed_mx = True
            elif result.find('does not exist') > 0:
                failed_mx = True
            else:
                failed_mx = False
            s.send("QUIT\n")
            break
        except smtplib.SMTPConnectError:
            continue

    if not failed_mx:
        return True
    return False
Exemple #20
0
	def srv_lookup(self, server):
		"""
		SRV resolver. Takes server=(host, port) as argument. Returns new (host, port) pair.
		"""
		if dns:
			query = "_xmpp-client._tcp.%s" % server[0]
			try:
				dns.DiscoverNameServers()
				dns__ = dns.Request()
				response = dns__.req(query, qtype="SRV")
				if response.answers:
					# Sort by priority, according to RFC 2782.
					answers = sorted(response.answers, key=lambda a: a["data"][0])
					(port, host) = answers[0]["data"][2:][:2]
					server = str(host), int(port)
			except dns.DNSError:
				self.DEBUG("An error occurred while looking up %s." % query, "warn")
		return server
Exemple #21
0
def dns_test(domain):
    try:
        domain = website_get_newUrl(domain)
        index = domain.find("/")
        if index != -1:
            domain = domain[0:index]
        domain = domain.replace('/', '')
        spix = domain.find(':')
        if spix != -1:
            domain = domain[0:spix]
        DNS.DiscoverNameServers()
        req = DNS.Request()
        ans = req.req(name=domain, qtype=DNS.Type.ANY)
        return ans.answers
    except Exception as e:
        log_error("dns_test():" + str(e) + str(domain))
        dnsresult = []
        return dnsresult
def _setup():
    # Get the path layout for Courier.
    try:
        ch = subprocess.Popen('courier-config', stdout=subprocess.PIPE)
    except OSError:
        pass
    else:
        for chOutLine in ch.stdout:
            try:
                (setting, valueN) = chOutLine.split('=', 1)
                value = valueN.strip()
            except:
                continue
            if setting in ('prefix', 'exec_prefix', 'bindir', 'sbindir',
                           'libexecdir', 'sysconfdir', 'datadir', 'localstatedir',
                           'mailuser', 'mailgroup', 'mailuid', 'mailgid'):
                globals()[setting] = value
        # Catch the exit of courier-config
        try:
            ch.wait()
        except OSError:
            pass
    # Get the version of Courier currently running.
    try:
        ch = subprocess.Popen(['%s/courier' % sbindir, '--version'],
                              stdout=subprocess.PIPE)
    except OSError:
        pass
    else:
        chOutLine = ch.stdout.readline()
        versOutput = chOutLine.split(' ')
        if versOutput[0] == 'Courier':
            global version
            version = versOutput[1]
        # Catch the exit of courier --version
        try:
            ch.wait()
        except OSError:
            pass
    # Initialize the DNS module
    if DNS:
        DNS.DiscoverNameServers()
Exemple #23
0
    def get_mx_records(domain):
        """
        Gets an array of MXRecords associated to the domain specified.

        :param domain:
        :return: [MXRecord]
        """

        DNS.DiscoverNameServers()
        request = DNS.Request()
        response = request.req(name=domain, qtype=DNS.Type.MX)

        mx_records = []
        for answer in response.answers:
            mx_records.append(
                MXRecord(priority=answer['data'][0],
                         exchange=answer['data'][1],
                         domain=domain))

        return sorted(mx_records, key=lambda record: record.priority)
Exemple #24
0
def can_send_email(domain):
    """
    Confirms that we own the domain and there's an mx record pointing
    to sendgrid for it.

    Inputs:
    :domain: Domain to be checked

    Outputs:
    :return: Boolean/None
        None: we don't control this domain
        False: we control this domain but no MX record has been created
        True: we control this domain and an MX record already exists
    """
    if not domain_exists(domain):
        return None

    DNS.DiscoverNameServers()
    mx_hosts = DNS.mxlookup(domain)
    return any(mx_host == 'mx.sendgrid.net' for _, mx_host in mx_hosts)
Exemple #25
0
def validate_email(email, check_mx=False, verify=False):
    """Indicate whether the given string is a valid email address
    according to the 'addr-spec' portion of RFC 2822 (see section
    3.4.1).  Parts of the spec that are marked obsolete are *not*
    included in this test, and certain arcane constructions that
    depend on circular definitions in the spec may not pass, but in
    general this should correctly identify any email address likely
    to be in use as of 2011."""
    try:
        assert re.match(VALID_ADDRESS_REGEXP, email) is not None
        check_mx |= verify
        if check_mx:
            if not DNS:
                raise Exception('For check the mx records or check if the '
                                'email exists you must have installed pyDNS '
                                'python package')
            DNS.DiscoverNameServers()
            hostname = email[email.find('@') + 1:]
            mx_hosts = DNS.mxlookup(hostname)
            for mx in mx_hosts:
                try:
                    smtp = smtplib.SMTP()
                    smtp.connect(mx[1])
                    if not verify:
                        return True
                    status, _ = smtp.helo()
                    if status != 250:
                        continue
                    smtp.mail('')
                    status, _ = smtp.rcpt(email)
                    if status != 250:
                        return False
                    break
                except smtplib.SMTPServerDisconnected:
                    # Server not permits verify user
                    break
                except smtplib.SMTPConnectError:
                    continue
    except (AssertionError, ServerError):
        return False
    return True
Exemple #26
0
def lookup_avatar_server(domain, https):
    """
    Extract the avatar server from an SRV record in the DNS zone

    The SRV records should look like this:

       _avatars._tcp.example.com.     IN SRV 0 0 80  avatars.example.com
       _avatars-sec._tcp.example.com. IN SRV 0 0 443 avatars.example.com
    """

    DNS.DiscoverNameServers()
    try:
        dns_request = DNS.Request(name=service_name(domain, https),
                                  qtype='SRV').req()
    except DNS.DNSError as message:
        print "DNS Error: %s" % message
        return None

    if 'NXDOMAIN' == dns_request.header['status']:
        # Not an error, but no point in going any further
        return None

    if dns_request.header['status'] != 'NOERROR':
        print "DNS Error: status=%s" % dns_request.header['status']
        return None

    records = []
    for answer in dns_request.answers:
        if (not 'data' in answer) or (not answer['data']):
            continue
        if (not answer['typename']) or (answer['typename'] != 'SRV'):
            continue

        srv_record = {'priority': int(answer['data'][0]),
                      'weight': int(answer['data'][1]),
                      'port': int(answer['data'][2]),
                      'target': answer['data'][3]}

        records.append(srv_record)

    return normalized_target(records, https)
Exemple #27
0
def record_combine(query, type):
    dict_a_record = {}
    try:
        if type == "A":
            type_query = DNS.Type.A
        elif type == "NS":
            type_query = DNS.Type.NS
        elif type == "CNAME":
            type_query = DNS.Type.CNAME
        elif type == "SOA":
            type_query = DNS.Type.SOA
        elif type == "PTR":
            type_query = DNS.Type.PTR
        elif type == "MX":
            type_query = DNS.Type.MX
        elif type == "TXT":
            type_query = DNS.Type.TXT
        DNS.DiscoverNameServers()
        reqobj = DNS.Request()
        answerobj_a = reqobj.req(name=query,
                                 qtype=type_query,
                                 server="222.194.15.253")
        if not len(answerobj_a.answers):
            dict_a_record = {type: ""}
        else:
            for item in answerobj_a.answers:
                if item['typename'] == "SOA":
                    dict_a_record[item['typename']] = soa_tuple_operate(
                        item['data'])
                else:
                    try:
                        if dict_a_record[item['typename']]:
                            dict_a_record[item['typename']] = dict_a_record[
                                item['typename']] + " " + item['data']
                    except:
                        dict_a_record[item['typename']] = item['data']
    except:
        dict_a_record = {type: ""}
    return dict_a_record
Exemple #28
0
def query_ttl(query):
    DNS.DiscoverNameServers()
    reqobj = DNS.Request()
    answerobj_a = reqobj.req(name=query,
                             qtype=DNS.Type.NS,
                             server="222.194.15.251")

    if not answerobj_a.answers:
        blank = ""
        return (blank, blank)
    else:
        return_ns = []
        for item in answerobj_a.answers:
            return_ns.append(item['data'])
        return_dict = []

        for items in answerobj_a.answers:
            server = items['data']
            query_2 = "www." + query
            answerobj_b = reqobj.req(name=query_2,
                                     qtype=DNS.Type.A,
                                     server=server)
            return_dict = return_dict + answerobj_b.answers
        if not return_dict:
            return_dict_2 = []
            for items in answerobj_a.answers:
                server = items['data']
                query_2 = "www." + query
                answerobj_c = reqobj.req(name=query_2,
                                         qtype=DNS.Type.CNAME,
                                         server=server)
                return_dict_2 = return_dict + answerobj_c.answers
            if not return_dict_2:
                return ("", "")
            else:
                return (return_ns, return_dict_2)
        else:
            return (return_ns, return_dict)
Exemple #29
0
def getrecordsfromnameserver(qstring, qtype, nslist):
    for ns in nslist:
        reqobj = DNS.Request(server=ns)
        try:
            answers = reqobj.req(name=qstring, qtype=qtype).answers
            if len(answers):
                return answers
        except DNS.Base.DNSError:
            pass
    return []


def nslookup(qstring, qtype, verbose=1):
    nslist = findnameservers(qstring)
    if nslist == None:
        raise RuntimeError, "Could not find namserver to use."
    if verbose:
        print "Using namservers:", ", ".join(nslist)
    return getrecordsfromnameserver(qstring, qtype, nslist)


if __name__ == "__main__":
    query = sys.argv[1]
    DNS.DiscoverNameServers()
    answers = nslookup(query, DNS.Type.ANY)
    if not len(answers):
        print "Not found."
    for item in answers:
        print "%-5s %s" % (item["typename"], item["data"])
def CheckDomain(DomainList, CDNList, IPList):
    DNS.DiscoverNameServers()
    reqobj = DNS.Request()
    reqobj.defaults['server'] = ['113.215.2.222']
    reg = 0
    Returndate = []
    MaxMum = len(IPList)
    for domain in DomainList:
        domain = domain.strip('\n')
        Returndomain = []
        j = False
        try:
            answerobj = reqobj.req(name=domain, qtype=DNS.Type.A)
            x = answerobj.answers
            if not x:
                Returndate.append(str(domain) + "," + "无A记录" + "," + "域名出网,")
                continue
        except Exception, e:
            print e
            continue
        for donequeries in x:
            i = 1
            if j:
                break
            if donequeries['typename'] == "CNAME":  # 判断是否含有CNAME
                DomainCname = donequeries['data']
                CDN = ProcessData(DomainCname, CDNList)
                if CDN:
                    Returndomain = domain + ',' + CDN
                else:
                    Returndomain = domain + ',' + DomainCname
            elif donequeries['typename'] == "A":
                re_ip = re.compile(
                    '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')  # 判断IP
                if re_ip.match(donequeries['data']):  # 直到IP停止
                    A = donequeries['data']
                    if Returndomain == []:
                        Returndomain = domain + ',' + '无CNAME'
                    if len(A) != 0:
                        try:
                            for LocalIp in IPList:
                                IP = str(LocalIp[1]).encode('utf-8')
                                if donequeries['data'] in IPy.IP(IP):
                                    Returndate.append(Returndomain + "," +
                                                      "网内已经覆盖,")
                                    j = True
                                    break
                                elif i == MaxMum:
                                    Returndate.append(Returndomain + "," +
                                                      "域名出网,")
                                    j = True
                                    break
                                i += 1

                        except Exception, e:
                            Returndate.append(
                                str(Returndomain) + "," + "异常域名" + "," +
                                "域名出网,")
                            print e
                            break
            else:
                Returndate.append(
                    str(Returndomain) + "," + "异常域名" + "," + "域名出网,")