2

Currently I am using pwd.getpwall(), which shows me the entire password database. But I just want the users accounts of the computer. And with using getpwall() I am unable to do this ...

if 'foo' in pwd.getpwall():
     do stuff

since pwd.getpwall() returns a list of objects. And if I wanted to check if a user exist I would have to do a loop. I assume there is an easier way to do this.

GaretJax
  • 7,462
  • 1
  • 38
  • 47
huan
  • 1,121
  • 2
  • 8
  • 6

3 Answers3

9

In the same page of the manual:

pwd.getpwnam(name)

Return the password database entry for the given user name.

This is the result for an existent and an inexistent user:

>>> import pwd
>>> pwd.getpwnam('root')
pwd.struct_passwd(pw_name='root', pw_passwd='*', pw_uid=0, pw_gid=0, pw_gecos='System Administrator', pw_dir='/var/root', pw_shell='/bin/sh')
>>> pwd.getpwnam('invaliduser')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'getpwnam(): name not found: invaliduser'

Therefore you can do:

try:
    pwd.getpwnam(name)
except KeyError:
    # Handle non existent user
    pass
else:
    # Handle existing user
    pass

Note: the in operator would do a loop anyways to check if a given item is in a list (ref).

GaretJax
  • 7,462
  • 1
  • 38
  • 47
1

pwd.getpwnam raises a KeyErrorif the user does not exist:

def getuser(name):
    try:
        return pwd.getpwnam(name)
    except KeyError:
        return None
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
0

You could use something like:

>>> [x.pw_name for x in pwd.getpwall()]

Store the list and just check for username in list

Facundo Casco
  • 10,065
  • 8
  • 42
  • 63