Search code examples
linuxbashldapldif

Bash How To Select Multiple Lines from ldif-type File based on dn


I am wondering how best to parse an ldif file (and ldif-like files) so that I can import each DN entry and its associated attributes into variables, without crossing over into other DNs and their attributes, as everything is in a single file.

Please how can this be done?

Thanks for helping a noob out.

Edit: An example ldif-like file looks something like this:

    dn: cn=admins,cn=groups,cn=accounts,dc=mydom,dc=com
    Group name: admins
    Description: Account administrators group
    GID: 721800000
    Member users: admin, user2, user1
    ipauniqueid: 2dafa3a2-b903-11e2-8a28-525400a60ac3
    objectclass: top, groupofnames, posixgroup, ipausergroup, ipaobject, nestedGroup

    dn: cn=editors,cn=groups,cn=accounts,dc=mydom,dc=com
    Group name: editors
    Description: Limited admins who can edit other users
    GID: 721800002
    Member users: user1
    ipauniqueid: 2dc4446a-b903-11e2-a2fa-525400a60ac3
    objectclass: top, groupofnames, posixgroup, ipausergroup, ipaobject, nestedGroup

    dn: cn=employees,cn=groups,cn=accounts,dc=mydom,dc=com
    Group name: employees
    Description: Default group for all Qrios employees
    GID: 721800006
    Member users: user2, user3
    ipauniqueid: 134ae6e0-b910-11e2-a7f3-525400a60ac3
    objectclass: top, groupofnames, nestedgroup, ipausergroup, ipaobject, posixgroup

I would like to be able to select sections of the file, based on the first keyword (dn), and import the values of the lines into variables so I can make use of them, and then move to the next section.


Solution

  • sina, I am working with the LDIF format quite a lot and bash just does not cut it. I would strongly advise you to start using perl or python with their respective LDAP modules:

    Just a small example of perl with its LDAP module:

    # Read in the LDIF file specified in $input_file
    my $ldif = Net::LDAP::LDIF->new($input_file, "r", onerror => 'warn', change => 1);
    #
    # Process the LDIF input file
    #
    while($entry = $ldif->read()) 
    {
            # Get the Member attribute
            my @mbr = $entry->get_value('Member');
            foreach my $value (@mbr)
            {
                   # Here you have a 'Member' value in $value, do what you want
            }
    }
    

    As you can see, this makes things quite simple. Also, these modules take into account all the different conventions within LDIF like abbreviated lines, changetypes, and so on.