Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to parse Common Name from Distinguished Name

I am attempting to parse (with sed) just First Last from the following DN(s) returned by the DSCL command in OSX terminal bash environment...

CN=First Last,OU=PCS,OU=guests,DC=domain,DC=edu

I have tried multiple regexs from this site and others with questions very close to what I wanted... mainly this question... I have tried following the advice to the best of my ability (I don't necessarily consider myself a newbie...but definitely a newbie to regex..)

DSCL returns a list of DNs, and I would like to only have First Last printed to a text file. I have attempted using sed, but I can't seem to get the correct function. I am open to other commands to parse the output. Every line begins with CN= and then there is a comma between Last and OU=.

Thank you very much for your help!

like image 825
Ben Avatar asked Dec 26 '22 21:12

Ben


1 Answers

I think all of the regular expression answers provided so far are buggy, insofar as they do not properly handle quoted ',' characters in the common name. For example, consider a distinguishedName like:

CN=Doe\, John,CN=Users,DC=example,DC=local

Better to use a real library able to parse the components of a distinguishedName. If you're looking for something quick on the command line, try piping your DN to a command like this:

    echo "CN=Doe\, John,CN=Users,DC=activedir,DC=local" | python -c 'import ldap; import sys; print ldap.dn.explode_dn(sys.stdin.read().strip(), notypes=1)[0]'

(depends on having the python-ldap library installed). You could cook up something similar with PHP's built-in ldap_explode_dn() function.

like image 109
Josh Kupershmidt Avatar answered May 19 '23 02:05

Josh Kupershmidt