开发者

Is there a clean way to check if a given user exists on a computer through python?

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 'fo开发者_开发百科o' 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.


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).


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

def getuser(name):
    try:
        return pwd.getpwnam(name)
    except KeyError:
        return None


You could use something like:

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

Store the list and just check for username in list

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜