本文整理汇总了Python中dns.resolver.Resolver类的典型用法代码示例。如果您正苦于以下问题:Python Resolver类的具体用法?Python Resolver怎么用?Python Resolver使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Resolver类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _isitup
def _isitup(self, url, return_status=False, redirects=0):
valid_url = self._makeurl(url)
if Resolver is not None:
r = Resolver()
host = urlparse(valid_url).netloc.split(":")[0]
try:
r.query(host)
except NoAnswer:
return (False, valid_url, u"No DNS A/CNAME-records for that domain")
except NXDOMAIN:
return False, valid_url, u"No such domain"
try:
status, reason, data, headers = self._request(valid_url, "HEAD")
if 300 <= status < 400 and self._get_header(headers, "location"):
if redirects > self.redirect_limit:
return False, valid_url, u"Redirect limit reached"
return self._isitup(self._get_header(headers, "location"), return_status, redirects + 1)
up = status < 300
if return_status:
reason = u"%(status)d %(reason)s" % {u"status": status, u"reason": reason}
return up, valid_url, reason
except HTTPException:
return False, valid_url, u"Server is not responding"
示例2: run
def run(self):
""" Run the handler thread """
print "*Ping* We've got a message!"
# Handle DNS request
resolver = Resolver(self.caching, self.ttl)
aliasRecords = []
addressRecords = []
# Read and resolve the questions one-by-one
questions = self.request.questions
for question in questions:
hostname = question.qname
(hostname, aliases, addresses) = resolver.gethostbyname(hostname)
for alias in aliases:
aliasData = dns.resource.RecordData.create(Type.CNAME, alias)
aliasRecord = dns.resource.ResourceRecord(hostname, Type.CNAME, Class.IN, 9001, aliasData) # TODO fix ttl
aliasRecords.append(aliasRecord)
for address in addresses:
addressData = dns.resource.RecordData.create(Type.A, address)
addressRecord = dns.resource.ResourceRecord(hostname, Type.A, Class.IN, 9001, addressData)
addressRecords.append(addressRecord)
# Crafting of the response
respHeader = self.request.header
respHeader.qr = 1
respHeader.qd_count = 0
respHeader.an_count = 1
respMessage = dns.message.Message(respHeader, [], addressRecords + aliasRecords, [], [])
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
respMessageByte = respMessage.to_bytes()
sock.sendto(respMessageByte, self.clientAddr)
print "Ended request: " + hostname
sock.close()
示例3: reverse_dns_lookup
def reverse_dns_lookup(input, timeout=3, server=''):
"""Perform a simple reverse DNS lookup, return results in a dictionary"""
assert _REVERSE_DNS_REGEX.search(
input), "Invalid address format: '{0}'".format(input)
resolver = Resolver()
resolver.timeout = float(timeout)
resolver.lifetime = float(timeout)
if server:
resolver.nameservers = [server]
try:
tmp = input.strip().split('.')
tmp.reverse()
inaddr = '.'.join(tmp) + ".in-addr.arpa"
records = resolver.query(inaddr, 'PTR')
return {
'name': records[0].to_text(),
'lookup': inaddr,
'error': '',
'addr': input,
}
except DNSException as e:
return {
'addrs': [],
'lookup': inaddr,
'error': repr(e),
'name': input,
}
示例4: check_dns
def check_dns(dns_to_check, dns_server, retries=90, wait=10, ip_to_check=None):
LOG.info("Cheking dns for {}...".format(dns_to_check))
resolver = Resolver()
resolver.nameservers = [dns_server]
LOG.info("CHECK DNS: dns to check {}".format(dns_to_check))
for attempt in range(0, retries):
LOG.info("Cheking dns for {}... attempt number {}...".format(
dns_to_check,
str(attempt + 1)
))
try:
answer = resolver.query(dns_to_check)
except DNSException:
pass
else:
ips = map(str, answer)
LOG.info("CHECK DNS: ips {}".format(ips))
LOG.info("CHECK DNS: ip to check {}".format(ip_to_check))
if (ip_to_check and ip_to_check in ips) or (not ip_to_check and ips):
return True
sleep(wait)
return False
示例5: connect
def connect (self):
resolver = Resolver()
resolver.nameservers = ['69.197.169.9'] #tunlr dns address
#resolver.nameservers = ['208.122.23.22'] #Unblock-US dns address
answer = resolver.query(self.host,'A')
self.host = answer.rrset.items[0].address
self.sock = socket.create_connection ((self.host, self.port))
示例6: make_client
def make_client(self, url):
o = self.options
headers = {'Connection': 'Keep-Alive' if o.keepalive else 'Close'}
resolver = Resolver(configure=False)
if o.dns:
resolver.nameservers = [o.dns]
u = urlparse.urlparse(url)
qname = u.hostname
answer = resolver.query(qname, rdtype=dns.rdatatype.A,
rdclass=dns.rdataclass.IN, tcp=False,
source=None, raise_on_no_answer=False)
if answer.response.answer:
ip = answer.response.answer[0].items[0].address
if u.port:
netloc = '%s:%d' % (ip, u.netloc.split(':')[1])
else:
netloc = ip
url = urlparse.urlunsplit((u[0], netloc, u[2], u[3], u[4]))
headers['Host'] = qname
client = HTTPClient.from_url(url, concurrency=o.concurrency,
connection_timeout=o.timeout,
network_timeout=o.timeout,
headers=headers,
ssl_options=dict(ssl_version=PROTOCOL_TLSv1,
cert_reqs=CERT_NONE)
)
return client
示例7: resolve
def resolve(self, event, record, host, nameserver):
ipaddr = re.compile(r"\d+\.\d+\.\d+\.\d+")
if not record:
if ipaddr.search(host):
host = from_address(host)
record = "PTR"
else:
record = "A"
resolver = Resolver()
if nameserver:
if not ipaddr.search(nameserver):
nameserver = resolver.query(nameserver, "A")[0].address
resolver.nameservers = [nameserver]
try:
answers = resolver.query(host, str(record))
except NoAnswer:
event.addresponse(u"I couldn't find any %(type)s records for %(host)s", {"type": record, "host": host})
return
except NXDOMAIN:
event.addresponse(u"I couldn't find the domain %s", host)
return
responses = []
for rdata in answers:
responses.append(unicode(rdata))
event.addresponse(u"Records: %s", human_join(responses))
示例8: connect
def connect (self):
resolver = Resolver()
resolver.nameservers = ['185.37.37.37'] #Unlocator dns address
#resolver.nameservers = ['69.197.169.9'] #tunlr dns address (Now losed down)
#resolver.nameservers = ['208.122.23.22'] #Unblock-US dns address (Premium DNS)
answer = resolver.query(self.host,'A')
self.host = answer.rrset.items[0].address
self.sock = socket.create_connection ((self.host, self.port))
示例9: __init__
def __init__(self):
self.resolver = Resolver()
self.resolver.use_edns(0, 0, 4096)
self.resolver.set_flags(flags.AD + flags.RD)
self.degraded = Resolver()
self.degraded.use_edns(0, 0, 4096)
self.degraded.set_flags(flags.CD + flags.RD)
示例10: test_noraise_dns_tcp
def test_noraise_dns_tcp(self):
# https://github.com/eventlet/eventlet/issues/499
expected_ip = "192.168.1.1"
with tests.dns_tcp_server(expected_ip) as dnsaddr:
resolver = Resolver()
resolver.nameservers = [dnsaddr[0]]
resolver.nameserver_ports[dnsaddr[0]] = dnsaddr[1]
response = resolver.query('host.example.com', 'a', tcp=True)
self.assertIsInstance(response, Answer)
self.assertEqual(response.rrset.items[0].address, expected_ip)
示例11: get_ip
def get_ip():
'''
Query specified domain myip.opends.com from resolver1.opendns.com &
resolver2.opendns.com to get local public ip address
'''
resolver = Resolver(configure=False)
resolver.nameservers = ['208.67.222.222', '208.67.220.220']
answers = resolver.query('myip.opendns.com', 'A')
for rdata in answers:
return str(rdata)
示例12: test_raise_dns_tcp
def test_raise_dns_tcp(self):
# https://github.com/eventlet/eventlet/issues/499
# None means we don't want the server to find the IP
with tests.dns_tcp_server(None) as dnsaddr:
resolver = Resolver()
resolver.nameservers = [dnsaddr[0]]
resolver.nameserver_ports[dnsaddr[0]] = dnsaddr[1]
with self.assertRaises(NoAnswer):
resolver.query('host.example.com', 'a', tcp=True)
示例13: get_nsset
def get_nsset(zone, server, bufsize):
nsset = { 'RRSIG' : False }
resolver = Resolver()
resolver.nameservers = [server]
resolver.use_edns(edns=True, ednsflags=dns.flags.DO, payload=bufsize)
response = resolver.query(zone, 'NS', dns.rdataclass.IN, True).response
for answer in response.answer:
for ans in answer.items:
if ans.rdtype == dns.rdatatype.NS:
nsset[ans.to_text()] = { 'A' : None, 'AAAA' : None, 'RRSIG' : None }
elif ans.rdtype == dns.rdatatype.RRSIG:
nsset['RRSIG'] = True
return nsset
示例14: get_resolver
def get_resolver(server=None):
if server is None:
server = Server.self()
resolver = Resolver()
resolver.reset()
resolvconf = StringIO()
if server.ipv4:
resolvconf.write('nameserver %s\n' % (server.ipv4,))
if server.ipv6:
resolvconf.write('nameserver %s\n' % (server.ipv6,))
resolver.read_resolv_conf(resolvconf)
return resolver
示例15: verify_site
def verify_site(site_id, retry_count=1):
"""Celery task to verify site ownership"""
from .models import Site
site = Site.objects.get(pk=site_id)
key = site.get_verification_key()
valid = False
# Check header, content and files for the verification key in some common
# URL variations
for url_template in url_templates:
url = url_template % {'domain': site.domain, 'key': key}
resp = requests.get(url, timeout=10)
if not resp.ok:
continue
valid = valid or key in resp.headers.get("X-Guardhouse-Verify", "")
valid = valid or key in resp.content
if valid:
break
if not valid:
# Still not valid - check DNS
resolver = Resolver()
try:
result = resolver.query("%s.%s." % (key, site.domain), rdatatype.CNAME)
try:
for answer in result.response.answer:
for item in answer.items:
if (isinstance(item, rdtypes.ANY.CNAME.CNAME) and
"verify.guardhous.es" in item.target.to_text()):
valid = True
raise StopIteration()
except StopIteration:
pass
except NXDOMAIN:
# Domain doesn't exist - nothing we can do
pass
from .models import VERIFY_STATE
if valid:
site.verification_state = VERIFY_STATE.VERIFIED
site.save()
return True
if retry_count >= 4:
# We already tried 3 times - time to give up
site.verification_state = VERIFY_STATE.FAILED
site.save()
# Fall trough - retry
verify_site.retry(countdown=30, args=(site_id, retry_count + 1))