misc-scripts/ips-from-spf.py
File Type: text/x-script.python
#!/usr/bin/env python
import dns.resolver
import argparse
def get_ip_addresses_from_spf(spf_record):
ip_addresses = []
mechanisms = spf_record.split()
for mechanism in mechanisms:
if mechanism.startswith('ip4:'):
ip_addresses.append(mechanism[4:])
elif mechanism.startswith('ip6:'):
ip_addresses.append(mechanism[4:])
elif mechanism.startswith('include:'):
sub_domain = mechanism[8:]
sub_spf_record = get_spf_record(sub_domain)
ip_addresses.extend(get_ip_addresses_from_spf(sub_spf_record))
return ip_addresses
def get_spf_record(domain):
try:
answers = dns.resolver.resolve(domain, 'TXT')
for rdata in answers:
for txt_string in rdata.strings:
if txt_string.startswith(b'v=spf1'):
return txt_string.decode()
except dns.resolver.NoAnswer:
return None
except dns.resolver.NXDOMAIN:
return None
parser = argparse.ArgumentParser("ips-from-spf")
parser.add_argument("domain", help="DNS domain to do an SPF lookup for")
args = parser.parse_args()
if args.domain:
spf_record = get_spf_record(args.domain)
ip_addresses = get_ip_addresses_from_spf(spf_record)
print(*ip_addresses, sep=",")
else:
print("No domain was specified.")