Skip to content

Instantly share code, notes, and snippets.

@joneskoo
Created February 16, 2011 11:03
Show Gist options
  • Save joneskoo/829206 to your computer and use it in GitHub Desktop.
Save joneskoo/829206 to your computer and use it in GitHub Desktop.
Validates that each IPv4/IPv6 address has a valid reverse DNS (including forward DNS)
#!/usr/bin/env python
import sys
from os.path import basename
from dns import resolver, reversename
import socket
def get_single_reverse(ip):
rname = reversename.from_address(ip)
try:
responses = resolver.query(rname, "PTR")
except:
print "%s\tNo reverse DNS" % ip
return None
if len(responses) > 1:
print "%s\tMultiple reverse DNS records" % ip
else:
return responses[0]
return None
def compare_ip(family, string1, string2):
a = socket.inet_pton(family, string1)
b = socket.inet_pton(family, string2)
return a == b
def check_forward(ip, rname):
try:
rname_aaaa = resolver.query(rname, "AAAA")
except:
rname_aaaa = []
try:
rname_a = resolver.query(rname, "A")
except:
rname_a = []
if ':' in ip:
if len(rname_aaaa) > 1:
print "%s\tMultiple IPs for forward name %s" % (ip, rname)
else:
if len(rname_aaaa) == 0:
print "%s\tForward name %s does not have an AAAA record" % (ip, rname)
elif not compare_ip(socket.AF_INET6, ip, rname_aaaa[0].address):
print "%s\tReverse name does not match forward name" % ip
elif len(rname_a) != 0:
print "%s\tIPv6 forward name %s has A records" % (ip, rname)
for i in rname_a:
print " - %s" % i.address
else:
print "%s\tOK" % ip
else:
if len(rname_a) > 1:
print "%s\tMultiple IPs for forward name %s" % (ip, rname)
else:
if not compare_ip(socket.AF_INET, ip, rname_a[0].address):
print "%s\tReverse name does not match forward name" % (ip)
elif len(rname_aaaa) != 0:
print "%s\tIPv4 forward name has AAAA records"
else:
print "%s\tOK" % ip
def main():
if len(sys.argv) != 2:
print "Usage: %s <IP-list-file>" % basename(sys.argv[0])
print
print "File format: one IP per line, IPv4 or IPv6"
sys.exit(1)
ip_list = open(sys.argv[1], 'r').readlines()
for ip in ip_list:
ip = ip.strip()
if ip == '':
continue
rname = get_single_reverse(ip)
if rname:
check_forward(ip, rname.target)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment