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.

107 lines
2.1 KiB

  1. #! /usr/bin/env python
  2. """Rebuild staff table in userdb from DCU's LDAP staff tree."""
  3. import ldap
  4. import pgdb
  5. import re
  6. __version__ = "$Revision$"
  7. __author__ = "Cillian Sharkey"
  8. def main():
  9. """Program entry function."""
  10. ldaphost = 'atlas.dcu.ie'
  11. dbh = pgdb.connect(database = 'userdb')
  12. cur = dbh.cursor()
  13. l = ldap.open(ldaphost)
  14. l.simple_bind_s('', '') # anonymous bind
  15. print 'userdb/staff:',
  16. print 'Search',
  17. staff = l.search_s('ou=staff,o=dcu', ldap.SCOPE_SUBTREE, 'objectclass=person', ('fullName', 'givenName', 'sn', 'mail', 'cn', 'gecos'))
  18. print '[%d].' % len(staff),
  19. # Delete all existing entries.
  20. #
  21. print 'Purge.',
  22. cur.execute('delete from staff')
  23. # Add new entries.
  24. #
  25. print 'Populate.',
  26. total = 0
  27. ids = {}
  28. insert_staff = "INSERT INTO staff (id, name, email) VALUES (%s, %s, %s)"
  29. re_gecos = re.compile(r'^(.*),.*(\d{8})')
  30. for i in staff:
  31. try:
  32. attr = i[1]
  33. id = name = None
  34. # Check gecos for full name and staff id.
  35. #
  36. if attr.has_key('gecos'):
  37. res = re_gecos.search(attr['gecos'][0])
  38. if res:
  39. name = res.group(1)
  40. id = int(res.group(2))
  41. # If no id in gecos, cycle through each cn attribute value
  42. # until we find one that is a number (which can only be the id
  43. # number).
  44. #
  45. if not id:
  46. if attr.has_key('cn'):
  47. for j in attr['cn']:
  48. try:
  49. id = int(j)
  50. except ValueError:
  51. pass
  52. else:
  53. break
  54. else:
  55. # No id found!
  56. continue
  57. # Ignore entries with duplicate IDs.
  58. #
  59. if ids.has_key(id):
  60. continue
  61. else:
  62. ids[id] = 1
  63. # If no name found from gecos and no fullName attribute,
  64. # construct their full name from first name ('givenName')
  65. # followed by their surname ('sn').
  66. #
  67. if not name:
  68. if attr.has_key('fullName'):
  69. name = attr['fullName'][0]
  70. else:
  71. name = '%s %s' % (attr['givenName'][0], attr['sn'][0])
  72. email = attr['mail'][0]
  73. cur.execute(insert_staff, (id, name, email))
  74. total += 1
  75. except KeyError, e:
  76. pass
  77. print 'Done [%d/%d].' % (total, len(staff))
  78. dbh.commit()
  79. cur.execute('END; VACUUM ANALYZE staff')
  80. dbh.close()
  81. l.unbind()
  82. if __name__ == "__main__":
  83. main()