python-3.xdomaincontrollerldap3

python ldap3 get domain controller list


I need some help with a script, I am trying to get a list of all the domain controllers for a domain. I am using python ldap3 and I am getting errors trying to connect. See below, any suggestions will be appreciated.

Code

#!/usr/bin/python3


from ldap3 import Server, Connection

# LDAP server configuration
ldap_server = 'ldap://company.com'
ldap_user = 'username'
ldap_password = 'mypassword'

# Connect to the LDAP server
server = Server(ldap_server, get_info=Server.info)
conn = Connection(server, ldap_user, ldap_password, auto_bind=True)

# Search for domain controllers
conn.search(search_base='CN=Domain Controllers,DC=company,DC=com',
            search_filter='(objectClass=computer)',
            attributes=['name'])

# Print the list of domain controllers
print("Domain Controllers:")
for entry in conn.entries:
    print(entry.name)

Output

Traceback (most recent call last):
  File "./query-dc-list4.py", line 13, in <module>
    conn = Connection(server, ldap_user, ldap_password, auto_bind=True)
  File "/usr/lib/python3.6/site-packages/ldap3/core/connection.py", line 356, in __init__
    self._do_auto_bind()
  File "/usr/lib/python3.6/site-packages/ldap3/core/connection.py", line 405, in _do_auto_bind
    raise LDAPBindError(error)

Solution

  • I just realized that my base search was incorrect. it should be the following

    conn.search(search_base='OU=Domain Controllers,DC=company,DC=com',
                search_filter='(objectClass=computer)',
                attributes=['name'])