Skip to content

Instantly share code, notes, and snippets.

@zekiahmetbayar
Created October 1, 2021 18:05
Show Gist options
  • Select an option

  • Save zekiahmetbayar/15c54ec461b460dfe5443c8a20e63e7f to your computer and use it in GitHub Desktop.

Select an option

Save zekiahmetbayar/15c54ec461b460dfe5443c8a20e63e7f to your computer and use it in GitHub Desktop.
Python-LDAP Basic Search
import ldap
class Test:
def __init__(self, dname, dip, sbase, uname, pword):
# Parameters
self.dip = dip # Domain IP Address
self.uname = uname # Ldap Username
self.pword = pword # Ldap User Password
self.dname = dname # Domain Name (Dot Format)
self.searchbase = sbase # Search Base
self.dn = "dc=" + ",dc=".join(dname.split(".")) # Domain Name (DC Format)
self.connect() # LDAP Connect
def connect(self):
# Connection data set
host = 'ldaps://' + self.dip + ':636'
binformation = self.uname + '@' + self.dname
try:
# LDAP option set
self.ldapConnection = ldap.initialize(host)
self.ldapConnection.set_option(ldap.OPT_NETWORK_TIMEOUT, 20.0)
self.ldapConnection.set_option(ldap.OPT_REFERRALS, 0)
self.ldapConnection.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
self.ldapConnection.simple_bind_s(binformation, self.pword)
logger.info('LDAP bağlantısı başarıyla kuruldu.')
print("Ldap connection successfull.")
except Exception as e:
print("Ldap connection failed. Error : " + str(e))
def search(self, fltr, attrs):
# LDAP Basic Search
try:
result = self.ldapConnection.search_s(self.searchbase, ldap.SCOPE_SUBTREE, fltr, attrs)
print("Search result : \n" + str(result))
except Exception as e:
print("Ldap search failed. Error : " + str(e))
# Usage
test = Test('home.lab', '10.0.0.1', 'CN=Users,DC=home,DC=lab', 'Administrator', 'Pass123!')
# return the name of those whose cn is admininstrator
test.search('cn=Administrator', ['name'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment