Skip to content

Instantly share code, notes, and snippets.

@Mostafa-Hamdy-Elgiar
Created February 24, 2017 17:50
Show Gist options
  • Save Mostafa-Hamdy-Elgiar/0ad365f294496217fcfdd1fa2f6f43df to your computer and use it in GitHub Desktop.
Save Mostafa-Hamdy-Elgiar/0ad365f294496217fcfdd1fa2f6f43df to your computer and use it in GitHub Desktop.
A Python Script to search in a MS AD
#!/usr/bin/env python
import ldap , sys
if len(sys.argv) != 2 :
pritn "Example of usage: python ADsearch.py <username>"
sys.exit(1)
username = sys.argv[1]
Server = "ldap://xxx.xxx.xxx.xxx"
DN = "cn=xxx,cn=xxx,dc=xxx,dc=xxx,dc=xxx,dc=" #a DN for the user using in auth process
Secret = "xxxxxx"
Base = "dc=xxxx,dc=xxx,dc=xxx,dc=xx" #The search domain level
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName=%s))" %username
Attrs = ["sAMAccountName","givenName","cn"]
l = ldap.initialize(Server)
l.protocal_version = 3
l.set_option(ldap.OPT_REFERRALS, 0)
l.simple_bind_s(DN, Secret)
res = l.search(Base, Scope, Filter, Attrs)
ress = l.result()
r = len(ress[1])
if r > 0:
print "exist"
else :
print "not exist"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment