]> git.zarvox.org Git - wp3.git/blob - ldapsearcher.py
Added Python docstrings for all classes.
[wp3.git] / ldapsearcher.py
1 import ldap
2
3 class LDAPSearcher():
4         def __init__(self):
5                 """Bind to the Texas A&M LDAP server."""
6                 server = "operator.tamu.edu"
7                 who = ""
8                 cred = ""
9                 self.l = ldap.open(server)
10                 self.l.simple_bind(who, cred)
11                 #print "bound successfully"
12
13         def lookup(self,username=""):
14                 """Look up person with netid <username> and return a dictionary of relevant attributes."""
15                 base = ""
16                 scope = ldap.SCOPE_SUBTREE
17                 filter = ""
18                 try:
19                         uin = int(username)
20                         filter = "tamuEduPersonUIN=" + username
21                 except:
22                         filter = "tamuEduPersonNetID=" + username
23                 retrieve_attributes = ["tamuEduPersonNetID", "sn", "givenName", "mail", "major", "classification"]
24                 count = 0
25                 result_set = []
26                 all = 0
27                 timeout = 5.0
28                 toreturn = {}
29                 #print "searching"
30                 result_id = self.l.search(base, scope, filter, retrieve_attributes)
31                 while True:
32                         try:
33                                 result_type, result_data = self.l.result(result_id, all, timeout)
34                                 if (result_data == []):
35                                         break
36                                 else:
37                                         if result_type == ldap.RES_SEARCH_ENTRY:
38                                                 result_set.append(result_data)
39                         except ldap.TIMEOUT:
40                                 return { "netid" : username }
41                 if len(result_set) == 0:
42                 #       print "No matching NetID"
43                         return {}
44                 toreturn["netid"] = username
45                 for i in range(len(result_set)):
46                         for entry in result_set[i]:
47                                 for attr in retrieve_attributes:
48                                         try:
49                                                 if entry[1][attr][0] == "":
50                                                         continue;
51                 #                               print attr,"=",entry[1][attr][0]
52                                                 toreturn[attr] = entry[1][attr][0]
53                                         except:
54                                                 pass
55                 #print result_set
56                 return toreturn
57
58 if __name__ == "__main__":
59         a = LDAPSearcher()
60         print a.lookup("drew.m.fisher")
61
62