Skip to content

Instantly share code, notes, and snippets.

@markbosky
Created May 23, 2024 18:04
Show Gist options
  • Save markbosky/8e68ecbe5dad3287cbcca1096d174eb9 to your computer and use it in GitHub Desktop.
Save markbosky/8e68ecbe5dad3287cbcca1096d174eb9 to your computer and use it in GitHub Desktop.
Check MX Records for a list of given domains
import dns.resolver
def get_mx_records(domain):
"""Get MX records for a given domain."""
try:
answers = dns.resolver.resolve(domain, 'MX')
mx_records = [(r.exchange.to_text(), r.preference) for r in answers]
return mx_records
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN, dns.resolver.Timeout) as e:
return f"Error retrieving MX records for {domain}: {str(e)}"
def main(domains_file):
"""Read domains from a file and print their MX records."""
try:
with open(domains_file, 'r') as file:
domains = file.readlines()
for domain in domains:
domain = domain.strip()
if domain: # Ensure the domain is not empty
mx_records = get_mx_records(domain)
print(f"Domain: {domain}")
if isinstance(mx_records, str):
print(mx_records)
else:
for record in mx_records:
print(f" MX: {record[0]}, Priority: {record[1]}")
print()
except FileNotFoundError:
print(f"Error: The file {domains_file} was not found.")
except Exception as e:
print(f"An unexpected error occurred: {str(e)}")
if __name__ == "__main__":
# Path to the file containing the list of domains (one per line)
domains_file = 'domains.txt'
main(domains_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment