Redbrick User management tool
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.0 KiB

  1. #! /usr/bin/env python
  2. """Rebuild students table in userdb from DCU's LDAP student tree."""
  3. import ldap
  4. import pgdb
  5. __version__ = "$Revision: 1.1 $"
  6. __author__ = "Cillian Sharkey"
  7. def main():
  8. """Program entry function."""
  9. ldaphost = 'atlas.dcu.ie'
  10. dbh = pgdb.connect(database = 'userdb')
  11. cur = dbh.cursor()
  12. l = ldap.open(ldaphost)
  13. l.simple_bind_s('', '') # anonymous bind
  14. print 'userdb/students:',
  15. print 'Search',
  16. students = l.search_s('ou=students,o=dcu', ldap.SCOPE_SUBTREE, 'objectclass=person', ('givenName', 'sn', 'mail', 'l', 'cn'))
  17. print '[%d].' % len(students),
  18. # Delete all existing entries.
  19. #
  20. print 'Purge.',
  21. cur.execute('delete from students')
  22. # Add new entries.
  23. #
  24. print 'Populate.',
  25. total = 0
  26. ids = {}
  27. insert_student = 'INSERT INTO students (id, name, email, course, year) VALUES (%d, %s, %s, %s, %s)'
  28. for i in students:
  29. try:
  30. attr = i[1]
  31. # Extract course & year from 'l' attribute value. Assumes last
  32. # character is the year (1, 2, 3, 4, X, O, C, etc.) and the rest is the
  33. # course name. Uppercase course & year for consistency.
  34. #
  35. course = attr['l'][0][:-1].upper() or 'N/A'
  36. year = attr['l'][0][-1].upper() or 'N/A'
  37. # Cycle through each 'cn' attribute value until we find one that is a
  38. # number (which can only be the id number).
  39. #
  40. for j in attr['cn']:
  41. try:
  42. id = int(j)
  43. except ValueError:
  44. pass
  45. else:
  46. break
  47. else:
  48. # No ID number found! Skip this ldap entry.
  49. continue
  50. if ids.has_key(id):
  51. continue
  52. else:
  53. ids[id] = 1
  54. # Construct their full name from first name ('givenName') followed by
  55. # their surname ('sn').
  56. #
  57. name = '%s %s' % (attr['givenName'][0], attr['sn'][0])
  58. email = attr['mail'][0]
  59. cur.execute(insert_student, (id, name, email, course, year))
  60. total += 1
  61. except KeyError:
  62. pass
  63. print 'Done [%d/%d].' % (total, len(students))
  64. dbh.commit()
  65. cur.execute('END; VACUUM ANALYZE students')
  66. dbh.close()
  67. l.unbind()
  68. if __name__ == "__main__":
  69. main()