Bash脚本保存ldapsearch使用自定义格式 - Bash script to save ldapsearch with custom format

- 此内容更新于:2015-12-20



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 <>
jdoe1=Jane Doe <>

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

echo `ldapsearch -x -h -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, dn: uid=jdoe,ou=Special Users,dc=company,dc=com cn: John Doe User mail: # jdoe1, People, dn: uid=jdoe1,ou=People,dc=company,dc=com cn: Jane Doe mail: # ....... # 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,


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

ldapsearch -LLL -x -h -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: ................... 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:"


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) }; } }'

(原文:Thanks, that is almost right, there are two minor problems, the first user's uid doesn't show up and also it writes everything in one line (which isn't bad but it'd be way easier and better to have each user on a new line).. Edit: Just to be clear with the -LLL it removes the first uid, but without -LLL it keeps the first user's uid but there's a = before it..)


(原文:The "NR>2" at the beginning of the awk script causes the first line of input to be skipped, so removing that should let you get the first user. However, I don't know why everything is written on one line; the "\n" after the final printf should cause each user to be printed on a separate line (assuming each user has an email address in angle brackets that is printed).)