Python – MX Scanner

# Author: Kerry Cordero
# Version: 1.0.0
# Description: This script will look at a file called "mx-records.txt" and run a DIG MX scan against it.  If it exists, it will be listed in green. If not, it show "No Record" in red. 

import os
import subprocess
from prettytable import PrettyTable
from termcolor import colored

# Function to perform a DNS MX record lookup using dig
def get_mx_record(domain):
        # Run the dig command to get MX records
        result = subprocess.check_output(['dig', '+short', 'MX', domain], text=True)
        # If the result is not empty, return it, otherwise return None
        return result.strip() if result.strip() else None
    except Exception as e:
        print(f"Error while executing dig command: {e}")
        return None

# Get the absolute directory path of this script
script_dir = os.path.dirname(os.path.abspath(__file__))

# Construct the absolute file path
file_path = os.path.join(script_dir, 'mx-records.txt')

# Read the list of FQDNs from the file
    with open(file_path, "r") as file:
        domains = [line.strip() for line in file.readlines()]
except FileNotFoundError:
    print(f"Error: File mx-records.txt not found in {script_dir}.")

# Create a table with PrettyTable
table = PrettyTable()
table.field_names = ["Domain", "MX Record"]

# Loop through each domain and perform a DNS MX record lookup
for domain in domains:
    mx_record = get_mx_record(domain)
    # If an MX record exists, add it to the table in green
    # Otherwise, add "No Record" in red
    if mx_record:
        table.add_row([domain, colored(mx_record, 'green')])
        table.add_row([domain, colored("No Record", 'red')])

# Display the table