ifxlookup/plugins/dns.py

72 lines
2.1 KiB
Python

from servicebase import ServiceBase
import socket
import ipaddress
import dns.resolver
class ServiceDelegate(ServiceBase) :
def get_arguments(cls) :
"""Returns an array of information used to construct an argumentparser argument."""
return [ '-d', '--dns', 'store_true', "Return DNS resolution about the subject (dns)" ]
def startup(self) :
self.resolver = dns.resolver.Resolver()
if 'resolver' in self.config :
self.resolver.nameservers.append(self.config['resolver'])
def perform_lookup(self,subject) :
# Note : hostname lookups always use system resolver.
# TODO: Make host lookups use the config-sepcified resolver.
try :
subjecttuple = socket.gethostbyname_ex(subject)
# Can't make an IP of the subject
except ValueError :
try :
# Lookup with system
subjecttuple = socket.gethostbyname_ex(subject)
except socket.gaierror :
# Not a valid host or IP
self.error.append("Unable to resolve " + subject)
subjecttuple = [subject,[],['']]
# Can't make IPv4 out of it
except socket.gaierror :
self.error.append("Unable to resolve " + subject)
subjecttuple = [subject,[],['']]
# Get additional records
return_dict = {}
mx = self.get_records(subjecttuple[0],'MX')
ns = self.get_records(subjecttuple[0],'NS')
txt = self.get_records(subjecttuple[0],'TXT')
mx.sort()
ns.sort()
txt.sort()
if mx and len(mx) > 0 :
return_dict.update({'mx':mx})
if ns and len(ns) > 0 :
return_dict.update({'ns':ns})
if txt and len(txt) > 0 :
return_dict.update({'txt':txt})
# Write final dictionary
if len(subjecttuple[2]) > 0 and subjecttuple[2][0] != '':
return_dict['addresses'] = list(subjecttuple[2])
if subjecttuple[0] and subjecttuple[0] != '' :
return_dict['name'] = subjecttuple[0]
if len(subjecttuple[1]) > 0 :
return_dict['aliases'] = list(subjecttuple[1])
return return_dict
def get_records(self,subject,recordtype) :
recs = []
try :
results = self.resolver.query(subject,recordtype)
for result in results :
recs.append(result.to_text())
return recs
except Exception as exception :
return recs