Last active
May 6, 2022 23:33
-
-
Save maxneuvians/9c4a8c509e92102726081b2958f3c66f to your computer and use it in GitHub Desktop.
Check if domain has MX record
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import random | |
import string | |
import urllib.request | |
import urllib.parse | |
url = "https://dns.google/resolve" | |
def get_mx_record(domain): | |
if validate_domain(domain): | |
params = { | |
"name": domain, | |
"type": "MX", | |
"edns_client_subnet": "0.0.0.0/0", | |
"random_padding": random_string() | |
} | |
data = urllib.parse.urlencode(params) | |
try: | |
with urllib.request.urlopen(url + "?" + data) as response: | |
response = json.loads(response.read()) | |
if response["Status"] == 0 and "Answer" in response: | |
return True | |
else: | |
return False | |
except Exception as e: | |
print(e) | |
def random_string(): | |
length = random.randint(10, 50) | |
return "".join(random.choice(string.ascii_lowercase) for _ in range(length)) | |
def validate_domain(domain): | |
domain = domain.lower().strip(".") | |
if not(1 <= len(domain) <= 253): | |
return False | |
for part in domain.split("."): | |
if not(1 <= len(part) <= 63): | |
return False | |
try: | |
domain.encode("idna") | |
return True | |
except UnicodeError: | |
return False | |
def handler(event, context): | |
domain = event["queryStringParameters"]["domain"] | |
(_, domain) = domain.split("@") | |
return {"statusCode": 200, "body": get_mx_record(domain)} | |
if __name__ == "__main__": | |
print(get_mx_record("google.com")) | |
print(get_mx_record("digital.canada.ca")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment