Tuesday, February 21, 2012

ldapsearch - exporting photos to named files

Simple requirement: export all staff photos from our LDAP repository. That bit is easy:

ldapsearch -h ldap -x -t -b "ou=People,dc=example,dc=com,dc=au"

But the files end up being called things like file:///tmp/ldapsearch-jpegPhoto-G4hm3V - not quite what we're after here. We want the pictures with the user ID as part of the name - e.g. pyarra.jpeg

After a bit of experimentation, I came up with this simple, elegant one-liner. OK, it's not all that simple, or elegant, but it is one-line. One long, ugly line:

ldapsearch -h ldap -t -x -b 'ou=People,dc=example,dc=com,dc=au'  uid | awk '$1 ~ /uid:/ {print $2}' | while read LUID; do ldapsearch -h ldap -t -x -b 'ou=People,dc=example,dc=com,dc=au' "uid=$LUID" jpegPhoto | (FILENAME=$(awk '$1 ~ /jpegPhoto:</ {print $2}' | sed -e 's/file:\/\///'); mv "$FILENAME" "/tmp/mugshots/$LUID.jpeg"); done

I probably should have bitten the bullet and done it as a Perl script. But that's the lure of the one-liner, eh? If I just go a little further, I'll have it!


  1. I managed to do it invoking ldapsearch only once:

    ldapsearch -t thumbnailPhoto=* thumbnailPhoto | while read line ; do echo $line | egrep -q "^dn:" && name=`echo $line | sed 's/.*CN=\([^,]\+\).*/\1/'` && read line && file=`echo $line | sed 's/.*file:\/\///'` && mv $file $name.jpg ; done

  2. I like your version much better, Mark! Thanks for sharing.