#!/usr/bin/python
#####################
# Author: Jacob Bresciani
# Date: June 29th 2012
#
#  This script will scrape the OU Users of an active directory domain 
# called ad.domain.local for any group starting nagios_, it will then
# create the groups in nagios format and include all users that exist
# in the AD version of the group. All groups are writen to the file
# /etc/nagios/objects/groups.cfg. 
#
####### NOTE ########
#
# In it's current form it will not do groups within groups, I'll look 
# at converting it to a recursive form later
#
#####################
import ldap

file = "/etc/nagios/objects/groups.cfg"
secret = "secret"
manager = "cn=nagios,ou=users,dc=ad,dc=domain,dc=local"
server = "ad.domain.local"
try:
    l = ldap.open(server)
    #l.set_option(ldap.OPT_REFERRALS, 0)
    l.simple_bind_s(manager, secret)
except ldap.LDAPError, error_message:
    print "Couldn't Connect. %s " % error_message

scope = ldap.SCOPE_SUBTREE
base = "CN=Users,DC=ad,DC=domain,DC=local"
retrieve_attributes = None
filter = "CN=nagios_*"
timeout = 0
count = 0
results = l.search_s(base, scope, filter, retrieve_attributes)
f = open(file, 'w')
for result in results:
    result_dn = result[0]
    result_attrs = result[1]
    group_members = []
    if "sAMAccountName" in result_attrs:
        for sAMAccountName in result_attrs["sAMAccountName"]:
            name = sAMAccountName.replace("nagios_", '')
            f.writelines("define contactgroup{\n\tcontactgroup_name %s\n" % name)
    if "description" in result_attrs:
        for description in result_attrs["description"]:
            f.writelines("\talias %s\n\tmembers " % description)
    if "member" in result_attrs:
        for member in result_attrs["member"]:
	    filter = "objectClass=user"
            mresults = l.search_s(member, scope, filter, retrieve_attributes)
            for mresult in mresults:
                mresult_dn = mresult[0]
                mresult_attrs = mresult[1]
                if "sAMAccountName" in mresult_attrs:
                    for sname in mresult_attrs["sAMAccountName"]:
                        #group_members.insert(0, sname)
                        f.writelines ("%s, " % sname)
    f.writelines("\n\t}\n\n")

f.close()
l.unbind_s()
