classify-users: determine type of Athena accounts
[user/alex/software/my-snippets.git] / classify-users
1 #!/usr/bin/python
2
3 import ldap
4 import ldap.filter
5 import sys
6
7 class LdapDirectory(object):
8     def __init__(self, ):
9         self.con = ldap.open('ldap-too.mit.edu')
10         self.con.simple_bind_s("", "")
11
12     def ldap_lookup(self, username):
13         dn = "ou=users,ou=moira,dc=mit,dc=edu"
14         fields = ['eduPersonAffiliation', 'mitDirStudentYear']
15         userfilter = ldap.filter.filter_format('uid=%s', [username])
16         result = self.con.search_s(dn, ldap.SCOPE_SUBTREE, userfilter, fields)
17         if len(result) > 0:
18             if len(result) > 1:
19                 print >>sys.stderr, "Unexpectedly received multiple results: %s" % (result, )
20             return result[0][1]
21         else:
22             return False
23
24 def classify(ldap_result):
25     secondary = "-"
26     if ldap_result == False:
27         primary = "unknown"
28     elif ldap_result == {}:
29         primary = "secret"
30     else:
31         primary = ldap_result['eduPersonAffiliation'][0]
32         secondary = ldap_result.get('mitDirStudentYear', ['-'])[0]
33     return primary, secondary
34
35 if __name__ == '__main__':
36     print >>sys.stderr, "Connecting to LDAP..."
37     directory = LdapDirectory()
38     print >>sys.stderr, "Starting lookups..."
39     for name in sys.stdin:
40         name = name.strip()
41         result = directory.ldap_lookup(name)
42         primary, secondary = classify(result)
43         print "%s\t%s\t%s" % (primary, secondary, name)