Skip to content

Instantly share code, notes, and snippets.

@mzupan
Last active September 1, 2016 16:10
Show Gist options
  • Save mzupan/7202254 to your computer and use it in GitHub Desktop.
Save mzupan/7202254 to your computer and use it in GitHub Desktop.
SPF dns lookup nagios check
#!/usr/bin/env python
#
# usage: ./check-spf.py domain.com
#
# author: [email protected]
#
#
import sys
try:
import dns.resolver
except:
print "Need to install dnspython"
sys.exit(1)
resolves = 0
def doResolve(host):
global resolves
answers = dns.resolver.query(host, 'TXT')
resolves += 1
for rdata in answers:
for part in str(rdata).split():
if "include" in part:
doResolve(part.split(":")[1])
elif part in ["a", "mx", "ptr", "exists"]:
resolves += 1
answers = dns.resolver.query(str(sys.argv[1]), 'TXT')
for rdata in answers:
for part in str(rdata).split():
if "include" in part:
doResolve(part.split(":")[1])
elif part in ["a", "mx", "ptr", "exists"]:
resolves += 1
if resolves > 10:
print "CRITICAL: Above the 10 allowed resolutions for SPF. You are at %i" % resolves
sys.exit(2)
print "OK: Below the 10 allowed resolutions for SPF. You are at %i" % resolves
sys.exit(0)
@mars64
Copy link

mars64 commented Sep 1, 2016

Hi there!

Thanks for this code, it was very helpful to me. I forked the gist to illustrate a change I think is worth integrating: https://gist.github.com/mars64/b723a82ce751a7ae49022f2e5f7abbd7#file-check-spf-py

Basically this adds support for multi-part DNS records, as per SPF RFC at https://tools.ietf.org/html/rfc7208#section-3.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment