Search code examples
regexlinuxbashldapldap-query

Bash script to save ldapsearch with custom format


I am trying to echo out every user on LDAP onto one text file but with a custom format:

The end goal is to have the following format:

uid=cn <mail>

So an example would be:

jdoe=John Doe <[email protected]>
jdoe1=Jane Doe <[email protected]>
...

I'm currently doing the following in terminal (Ubuntu 14.04):

echo `ldapsearch -x -h 127.0.0.1 -b "dc=company,dc=com" uid=* cn mail` >> ldap-users.txt

Which is getting everything I need however the format is as follows:

# extended LDIF # # LDAPv3 # base <dc=company,dc=com> with scope subtree # filter: uid=* # requesting: cn mail # # jdoe, Special Users, company.com dn: uid=jdoe,ou=Special Users,dc=company,dc=com cn: John Doe User mail: [email protected] # jdoe1, People, company.com dn: uid=jdoe1,ou=People,dc=company,dc=com cn: Jane Doe mail: [email protected] # ....... # search result search: 2 result: 0 Success # numResponses: 1387 # numEntries: 1386

NOTE: That that's all spit out in one line.

Any help is appreciated,

Thanks

EDIT: So by researching more I found out I can do:

ldapsearch -LLL -x -h 127.0.0.1 -b "dc=covisint,dc=com" uid=* cn mail

Which by adding -LLL it will not print ldap comments on output. Which results in the following format:

dn: uid=jdoe,ou=Special Users,dc=company,dc=com cn: John Doe User mail: [email protected] ................... dn: blahblahblha... etc

So that helps alot, now if there's a way to remove the "uid=" and the ",ou=...,dc=company,dc=com" and "cn:" and "mail:"


Solution

  • It's not particularly elegant, but piping the output of the ldapsearch command through the following seems to work for the quick and dirty test I just tried:

    | sed 's/uid=/\nuid=/'g | awk 'NR>2 { for( i=1; i<=NF; i++ ) { if ( $i ~ /uid=/ ) { printf "%s=", substr( $i, 5, index( $i, "," ) - 5 ) }; if ( $i ~ /cn:/ ) { printf "%s %s ", $(i+1), $(i+2) }; if ( $i ~ /mail:/ ) { printf "<%s>\n", $(i+1) }; } }'