1

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.

3 Answers 3

3

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

$
2

You could use awk on the output of getent passwd:

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

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.

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.