0

Given a system where the user data comes from e.g. an OpenLDAP database and is not in the /etc/passwd file. Is it possible to search through the getent passwd database and look up the user id/name by specifying (a part of) the full name?

E.g. getent passwd newbie gives me the following entry

newbie:x:1000:1000:firstname lastname:/home/newbie:/bin/zsh

How can I find all users with "lastname"? Is there something like getpwnam for the gecos field?

Note: I can not use just getent passwd (with no username) and then parse that since my database is too big.

2

I have not found a way to search the database, but looking up entries in OpenLDAP directly works for me.

$ ldapsearch -x -h ldap.example.com -ZZ \
             -D cn=lookup,dc=example,dc=com -W \
             -b ou=People,dc=example,dc=com -LLL \
             sn=lastname uid
dn: uid=newbie,ou=People,dc=example,dc=com  
uid: newbie

$
1

You could use awk on the output of getent passwd:

getent passwd | awk -F: '$5 ~ /lastname/ {print $1}'
  • oh, i should have clarified that the database is too large to output everything with getent passwd – Stefan Apr 19 '18 at 3:33
  • Oh, I see. In that case you'll have to use database-specific tools (like you already are). – Olorin Apr 19 '18 at 4:23
1

You could use something like the following sed command:

$ SURNAME=Smith
$ getent passwd | sed -n '/'$SURNAME'/s/^\([^:]*\):\([^:]*\):\([^:]*\):\([^:]*\):\([[:alpha:]]\+ '$SURNAME'\):\([^:]*\):\([^:]*\)$/\1 (\5)/p'
$ fps (Finnbarr Smith)
  jms (James Smith)
$

The above 'sed` regex assumes that the GECOS field contains exactly <FIRSTNAME><SPACE><LASTNAME>, e.g. "James Smith", as per your question. It can easily be modified to accommodate other GECOS field layouts.

  • The user mentioned in another comment that they were unable to use getent passwd since the database was too big. – Kusalananda Apr 19 '18 at 5:37
  • @Kusalananda. Ah, the user added that comment after I read their question. – fpmurphy Apr 19 '18 at 5:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.