LDAPsearch sanitize output

ldapsearch is a handy command line tool to query a ldap server, it does have some annoying quirks though;

  • The output is wrapped at 80 characters making it difficult to work with
  • Results containing utf8 characters are base64 encoded making it hard to read

An example of the output:

 

# extended LDIF
#
# LDAPv3
# base <ou=TestGroup,dc=example,dc=com> with scope subtree
# filter: (objectclass=groupOfNames)
# requesting: cn member
# with dereference control
#

# OC_USER, TestGroup, example.com
dn: cn=OC_USER,ou=TestGroup,dc=example,dc=com
member: cn=admin,dc=users,dc=example,dc=com
member: cn=nagios,dc=SYSTEM,dc=users,dc=example,dc=com
member: cn=Test User 1,ou=Developers ICT,dc=example,dc=com
member: cn=Test User 2,dc=users,dc=example,dc=com
member: cn=Test User 3,ou=Developers ICT,dc=example,dc=com
member: cn=John Jason Doe,ou=Project Management & Project Operations,dc=example
,dc=LOCAL
member:: Y249cmVuw6llLnBvaXLDqSxkYz11c2VycyxkYz1leHRlcm5hbCxkYz1MT0NBTA==
cn: OC_USER

# OC_ADMIN, TestGroup, example.com
dn: cn=OC_ADMIN,ou=TestGroup,dc=example,dc=com
cn: OC_ADMIN
member: cn=admin,dc=users,dc=example,dc=com
member: cn=Test User 1,ou=Developers ICT,dc=example,dc=com

# search result
search: 2
result: 0 Success

# numResponses: 3
# numEntries: 2

As you can see this can be hard to work with if you have to parse this further.

 

The following script will restore the wrapped lines and will decode the base64 encoded fields;

ldapsearch -h localhost -p 389 -D "CN=admin,DC=example,DC=com" -W -b "dc=example,dc=com" \
  -E 'deref=member:cn,uid' "(objectclass=groupOfNames)" cn member \
  | perl -MMIME::Base64 -n -00 -e 's/\n //g;s/(?<=:: )(\S+)/decode_base64($1)/eg;print'

This will produce the following:

# extended LDIF
#
# LDAPv3
# base <ou=TestGroup,dc=example,dc=com> with scope subtree
# filter: (objectclass=groupOfNames)
# requesting: cn member
# with dereference control
#

# OC_USER, TestGroup, example.com
dn: cn=OC_USER,ou=TestGroup,dc=example,dc=com
member: cn=admin,dc=users,dc=example,dc=com
member: cn=nagios,dc=SYSTEM,dc=users,dc=example,dc=com
member: cn=Test User 1,ou=Developers ICT,dc=example,dc=com
member: cn=Test User 2,dc=users,dc=example,dc=com
member: cn=Test User 3,ou=Developers ICT,dc=example,dc=com
member: cn=John Jason Doe,ou=Project Management & Project Operations,dc=example,dc=com
member:: cn=renée.poiré,dc=users,dc=example,dc=com
cn: OC_USER

# OC_ADMIN, TestGroup, example.com
dn: cn=OC_ADMIN,ou=TestGroup,dc=example,dc=com
cn: OC_ADMIN
member: cn=admin,dc=users,dc=example,dc=com
member: cn=Test User 1,ou=Developers ICT,dc=example,dc=com

# search result
search: 2
result: 0 Success

# numResponses: 3
# numEntries: 2

Leave a Reply