Python: get information from AD (ldap protocol)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env python

import ldap, sys

#example.msk
srv_example = 'ldap://172.16.0.12'
user_example = 'brownie'
pass_example = 'Eir2xooP'
dn_example = 'dc=example,dc=msk'

filter = '(&(objectClass=user)(samaccountname='+sys.argv[1]+'))'

conn = ldap.initialize(srv_example)
conn.protocol_version=3
conn.set_option(ldap.OPT_REFERRALS,0)
try:
        conn.bind_s(user_example, pass_example)
except ldap.INVALID_CREDENTIALS:
        print "username or password is incorrect."
        sys.exit()

res_id = conn.search_s(dn_example, ldap.SCOPE_SUBTREE, filter,['mail'])
for entry in res_id:
        print entry[1]
conn.unbind()