ipeacocks
ipeacocks

Reputation: 2317

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: [email protected]
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

Upvotes: 2

Views: 5678

Answers (2)

Niranjan M.R
Niranjan M.R

Reputation: 351

You could try the below method too:

class MyLDIF(ldif.LDIFParser):
   def __init__(self, input):
      ldif.LDIFParser.__init__(self,input)

   def handle(self,dn,entry):
      ldif = modlist.addModlist(entry)
      l = ldap.open('localhost', 389)
      try:
          l.bind("cn=Manager,dc=exapmle,dc=org", "Secret123")
      except ldap.SERVER_DOWN, e:
          print "ldap server is down"
      else:
          l.add_s(dn, ldif)

 def enable_schema():
    parser = MyLDIF(open('/tmp/a1.ldif', 'rb'))
    parser.parse()

I have derived to the above solution using example given in python-ldap docs

Upvotes: 1

dhke
dhke

Reputation: 15388

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)

Upvotes: 6

Related Questions