pythonopenldappython-ldapldif

Python-Ldap lib. Import LDIF


Is it possible to import LDIF like that

dn: cn=vpupkin,cn=people,ou=company,dc=domain,dc=com
c: UA
cn: vpupkin
employeetype: Indoor Front-end developer
gidnumber: 500
givenname: Vasya
homedirectory: /home/vpupkin
host: example.com
l: Kyiv
loginshell: /bin/bash
mail: vpupkin@domain.com
o: Microsoft
objectclass: inetOrgPerson
objectclass: posixAccount
objectclass: top
objectclass: shadowAccount
objectclass: ldapPublicKey
objectclass: extensibleObject
labeleduri: skype://test
sn: Pupkin
sshpublickey: ssh-rsa key
st: Trudova, 15
telephonenumber: 7777777777
uid: vpupkin
uidnumber: 1000
userpassword: {SHA}fEqNCco3Yq9h5ZUglD3CZJT4lBs=

using python-ldap library (http://www.python-ldap.org/)?

Yes, I can add new record to LDAP in such way http://www.grotan.com/ldap/python-ldap-samples.html#add but I am not sure about such text ldif-file.

PS. Full answer is here http://pastebin.com/eQU7xBfj


Solution

  • python-ldap contains an LDIF Parser module. Use that to parse the LDIF and submit the resulting dictionary to ldap_connection.add_s().

    Example usage:

    from StringIO import StringIO
    import ldif
    from ldap import modlist
    
    ldif_file = StringIO("""dn: cn=vpupkin,cn=people,ou=company,dc=domain,dc=com
    c: UA
    cn: vpupkin
    """)
    
    parser = ldif.LDIFRecordList(ldif_file)
    parser.parse()
    
    for dn, entry in parser.all_records:
        add_modlist = modlist.addModlist(entry)
        ldap_conn.add_s(dn, add_modlist)