Reputation: 140
I know that I can do this by querying AD again inside the loop, but that will generate a significant number of calls that I'm hoping to avoid. Here's my code:
import os, sys
import re
import datetime
import getpass
import ldap
debug = True
now = datetime.datetime.now()
print '******************\n##########\n******************\n'
l = ldap.initialize("ldap://##########")
if debug:
l.simple_bind_s("ADuser@##########","##########")
else:
try:
username = raw_input('Username: ')
password = getpass.getpass('Password: ')
l.simple_bind_s(username + '@##########', password)
except ldap.LDAPError, e:
print e
raw_input('Press any key to continue')
sys.exit()
baseDN = "OU=##########, OU=##########, OU=##########, DC=##########, DC=##########"
searchScope = ldap.SCOPE_SUBTREE
retrieveAttributes = None
searchFilter = "CN=*"
try:
ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
try:
f = open(os.environ['userprofile'] + '\\Desktop\\' + now.strftime('%Y-%m-%d') + '_Report.csv', 'w')
f.write('Full Name, Shared Account Name, Shared Account Code\n')
try:
for i in range(len(result_set)):
for entry in result_set[i]:
#print entry[1]['cn'][0] #Security Group name
try:
if entry[1]['member']:
for member in entry[1]['member']: #Group members
m = re.search('CN=(.+?),OU', member).group(1)
account = entry[1]['cn'][0]
description = entry[1]['description'][0].rstrip('\n')
member = m.replace('\\', '')
f.write('"' + member + '", ' + description + ', ' + account + '\n')
except:
pass
finally:
f.close()
except IOError, e:
print e
l.unbind_s()
except ldap.LDAPError, e:
print e
raw_input('Press any key to continue')
How can I pull the list of Security Groups, Members, and then also grab the individual user's sAMAccountName as well? Or is it just not possible without another lookup?
Upvotes: 0
Views: 732
Reputation: 11026
Though the LDAP protocol there is no ability to perform the action you are asking.
You of course, could simplify the code layout by making a method call to obtain sAMAccountName from the DN you find listed in the group.
These kind of actions are typical within LDAP but they happen very fast.
Upvotes: 1