PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/iRedMail/tools/create_mail_user_OpenLDAP.py

https://code.google.com/p/iredmail/
Python | 231 lines | 190 code | 10 blank | 31 comment | 3 complexity | f5bf86c8c003b916fcc76c74fb8e2596 MD5 | raw file
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Author: Zhang Huangbin <zhb(at)iredmail.org>
  4. # Purpose: Add new OpenLDAP user for postfix mail server.
  5. # Project: iRedMail (http://www.iredmail.org/)
  6. # --------------------------- WARNING ------------------------------
  7. # This script only works under iRedMail >= 0.4.0 due to ldap schema
  8. # changes.
  9. # ------------------------------------------------------------------
  10. # ---------------------------- USAGE -------------------------------
  11. # Put your user list in a csv format file, e.g. users.csv, and then
  12. # import users listed in the file:
  13. #
  14. # $ python create_mail_user_OpenLDAP.py users.csv
  15. #
  16. # ------------------------------------------------------------------
  17. # ------------------------- SETTINGS -------------------------------
  18. # LDAP server address.
  19. LDAP_URI = 'ldap://127.0.0.1:389'
  20. # LDAP base dn.
  21. BASEDN = 'o=domains,dc=iredmail,dc=org'
  22. # LDAP bind dn & password.
  23. #BINDDN = 'cn=Manager,dc=iredmail,dc=org'
  24. #BINDPW = 'passwd'
  25. # Storage base directory.
  26. STORAGE_BASE_DIRECTORY = '/var/vmail/vmail1'
  27. STORAGE_NODE = STORAGE_BASE_DIRECTORY.split('/')[-1]
  28. # Hashed maildir: True, False.
  29. # Example:
  30. # domain: domain.ltd,
  31. # user: zhang (zhang@domain.ltd)
  32. #
  33. # - hashed: d/do/domain.ltd/z/zh/zha/zhang/
  34. # - normal: domain.ltd/zhang/
  35. HASHED_MAILDIR = True
  36. # ------------------------------------------------------------------
  37. import os
  38. import sys
  39. import time
  40. import re
  41. try:
  42. import ldap
  43. import ldif
  44. except ImportError:
  45. print '''
  46. Error: You don't have python-ldap installed, Please install it first.
  47. You can install it like this:
  48. - On RHEL/CentOS 5.x:
  49. $ sudo yum install python-ldap
  50. - On Debian & Ubuntu:
  51. $ sudo apt-get install python-ldap
  52. '''
  53. sys.exit()
  54. def usage():
  55. print '''
  56. CSV file format:
  57. domain name, username, password, [common name], [quota], [groups]
  58. Example #1:
  59. iredmail.org, zhang, secret_pw, Zhang Huangbin, 1024, group1:group2
  60. Example #2:
  61. iredmail.org, zhang, secret_pw, Zhang Huangbin, ,
  62. Example #3:
  63. iredmail.org, zhang, secret_pw, , 1024, group1:group2
  64. Note:
  65. - Domain name, username and password are REQUIRED, others are optional:
  66. + common name.
  67. * It will be the same as username if it's empty.
  68. * Non-ascii character is allowed in this field, they will be
  69. encoded automaticly. Such as Chinese, Korea, Japanese, etc.
  70. + quota. It will be 0 (unlimited quota) if it's empty.
  71. + groups.
  72. * valid group name (hr@a.cn): hr
  73. * incorrect group name: hr@a.cn
  74. * Do *NOT* include domain name in group name, it will be
  75. appended automaticly.
  76. * Multiple groups must be seperated by colon.
  77. - Leading and trailing Space will be ignored.
  78. '''
  79. def convEmailToUserDN(email):
  80. """Convert email address to ldap dn of normail mail user."""
  81. if email.count('@') != 1: return ''
  82. user, domain = email.split('@')
  83. # User DN format.
  84. # mail=user@domain.ltd,domainName=domain.ltd,[LDAP_BASEDN]
  85. dn = 'mail=%s,ou=Users,domainName=%s,%s' % (email, domain, BASEDN)
  86. return dn
  87. def ldif_mailuser(domain, username, passwd, cn, quota, groups=''):
  88. DATE = time.strftime('%Y.%m.%d.%H.%M.%S')
  89. if quota == '':
  90. quota = '0'
  91. # Remove SPACE in username.
  92. username = str(username).strip().replace(' ', '')
  93. if cn == '': cn = username
  94. mail = username.lower() + '@' + domain
  95. dn = convEmailToUserDN(mail)
  96. # Get group list.
  97. if groups.strip() != '':
  98. groups = groups.strip().split(':')
  99. for i in range(len(groups)):
  100. groups[i] = groups[i] + '@' + domain
  101. maildir_domain = str(domain).lower()
  102. if HASHED_MAILDIR is True:
  103. # Hashed. Length of domain name are always >= 2.
  104. #maildir_domain = "%s/%s/%s/" % (domain[:1], domain[:2], domain)
  105. if len(username) >= 3:
  106. maildir_user = "%s/%s/%s/%s-%s/" % (username[0], username[1], username[2], username, DATE,)
  107. elif len(username) == 2:
  108. maildir_user = "%s/%s/%s/%s-%s/" % (
  109. username[0],
  110. username[1],
  111. username[1],
  112. username,
  113. DATE,
  114. )
  115. else:
  116. maildir_user = "%s/%s/%s/%s-%s/" % (
  117. username[0],
  118. username[0],
  119. username[0],
  120. username,
  121. DATE,
  122. )
  123. mailMessageStore = maildir_domain + '/' + maildir_user
  124. else:
  125. mailMessageStore = "%s/%s-%s/" % (domain, username, DATE)
  126. homeDirectory = STORAGE_BASE_DIRECTORY + '/' + mailMessageStore
  127. mailMessageStore = STORAGE_NODE + '/' + mailMessageStore
  128. ldif = [
  129. ('objectClass', ['inetOrgPerson', 'mailUser', 'shadowAccount', 'amavisAccount',]),
  130. ('mail', [mail]),
  131. ('userPassword', [passwd]),
  132. ('mailQuota', [quota]),
  133. ('cn', [cn]),
  134. ('sn', [username]),
  135. ('uid', [username]),
  136. ('storageBaseDirectory', [STORAGE_BASE_DIRECTORY]),
  137. ('mailMessageStore', [mailMessageStore]),
  138. ('homeDirectory', [homeDirectory]),
  139. ('accountStatus', ['active']),
  140. ('mtaTransport', ['dovecot']),
  141. ('enabledService', ['mail', 'smtp', 'smtpsecured',
  142. 'pop3', 'pop3secured', 'imap', 'imapsecured',
  143. 'deliver', 'lda', 'forward', 'senderbcc', 'recipientbcc',
  144. 'managesieve', 'managesievesecured', 'internal',
  145. 'sieve', 'sievesecured', 'shadowaddress',
  146. 'displayedInGlobalAddressBook', ]),
  147. ('memberOfGroup', groups),
  148. ]
  149. return dn, ldif
  150. if len(sys.argv) != 2 or len(sys.argv) > 2:
  151. print """Usage: $ python %s users.csv""" % ( sys.argv[0] )
  152. usage()
  153. sys.exit()
  154. else:
  155. CSV = sys.argv[1]
  156. if not os.path.exists(CSV):
  157. print '''Erorr: file not exist:''', CSV
  158. sys.exit()
  159. ldif_file = CSV + '.ldif'
  160. # Remove exist LDIF file.
  161. if os.path.exists(ldif_file):
  162. print '''< INFO > Remove exist file:''', ldif_file
  163. os.remove(ldif_file)
  164. # Read user list.
  165. userList = open(CSV, 'rb')
  166. # Convert to LDIF format.
  167. for entry in userList.readlines():
  168. entry = entry.rstrip()
  169. domain, username, passwd, cn, quota, groups = re.split('\s?,\s?', entry)
  170. dn, data = ldif_mailuser(domain, username, passwd, cn, quota, groups)
  171. # Write LDIF data.
  172. result = open(ldif_file, 'a')
  173. ldif_writer = ldif.LDIFWriter(result)
  174. ldif_writer.unparse(dn, data)
  175. # Notify info.
  176. print "< INFO > User data are stored in %s, you can verify it before import it." % os.path.abspath(ldif_file)
  177. # Prompt to import user data.
  178. '''
  179. Would you like to import them now?""" % (ldif_file)
  180. answer = raw_input('[Y|n] ').lower().strip()
  181. if answer == '' or answer == 'y':
  182. # Import data.
  183. conn = ldap.initialize(LDAP_URI)
  184. conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3) # Use LDAP v3
  185. conn.bind_s(BINDDN, BINDPW)
  186. conn.unbind()
  187. else:
  188. pass
  189. '''