Skip to content

Instantly share code, notes, and snippets.

@jankowa
Created January 16, 2015 21:22
Show Gist options
  • Save jankowa/99a0c8bf398929528894 to your computer and use it in GitHub Desktop.
Save jankowa/99a0c8bf398929528894 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import sys
from ldif import LDIFParser,LDIFWriter
import StringIO
user_entries = ['uid', 'uidNumber', 'sn', 'cn', 'loginShell','gidNumber', 'userPassword', 'homeDirectory','givenName', 'displayname'];
group_cns = ["group1","group2","group3"]
users= {};
renamed_users = {};
groups = {};
class IMPORT_LDIF(LDIFParser):
def __init__(self,input,output):
LDIFParser.__init__(self,input)
def handle(self,dn,entry):
if (entry.has_key('objectClass') and ('posixAccount' in entry['objectClass']) and entry['uid'][0]>=2000):
#print
new_dn = "uid=" + entry['uid'][0] + ",ou=people,dc=example,dc=com"
#print new_dn
new_entry = {};
new_entry['objectClass'] = ['top','person','inetorgperson','kolabinetorgperson','mailrecipient','organizationalperson','posixaccount'];
for (key,value) in entry.iteritems() :
if key in user_entries :
new_entry[key] = value;
renamed_users[dn] = new_dn;
users[new_dn] = new_entry;
if (entry.has_key('objectClass') and ('posixGroup' in entry['objectClass']) and (entry['cn'][0] in group_cns)):
groups[dn] = entry;
# "# extended LDIF"
# "#"
# "# LDAPv3"
# ""
# "changetype: add"
parser = IMPORT_LDIF(open("openldap-export.ldif", 'rb'), sys.stdout)
parser.parse()
##### Write the Header to output
output = StringIO.StringIO()
output.write(
"""# extended LDIF
#
# LDAPv3
""");
##### Write groups to output
writer = LDIFWriter(output);
for (dn,entry) in groups.iteritems() :
entry['member'] = [renamed_users[member] for member in entry['member'] ]
entry['objectClass'] = ['top', 'posixGroup', 'groupOfNames']
del entry['sambaGroupType']
del entry['sambaSID']
new_dn = "cn=" + entry['cn'][0] + ",ou=groups,dc=example,dc=com"
writer.unparse(new_dn, entry)
##### write users to output
for (dn,entry) in users.iteritems() :
writer.unparse(dn,entry)
##### Add the changetype commands
output = output.getvalue();
for line in output.splitlines(True) :
sys.stdout.write(line)
if line.startswith("dn") :
sys.stdout.write("changetype: add\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment