有没有一种干净的方法可以通过python检查计算机上是否存在给定的用户?

2024-05-14 05:52:28 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我正在使用pwd.getpwall(),它显示了整个密码数据库。但我只需要电脑的用户帐户。使用getpwall()我无法做到。。。在

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

因为pwd.getpwall()返回对象列表。如果我想检查用户是否存在,我必须做一个循环。我想有一个更简单的方法。在


Tags: 对象用户in数据库密码列表iffoo
3条回答

the same page of the manual

pwd.getpwnam(name)

Return the password database entry for the given user name.

这是现有用户和不存在用户的结果:

>>> 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'

因此,您可以:

^{pr2}$

注意:in运算符无论如何都会执行一个循环来检查给定的项是否在列表(ref)中。在

如果用户不存在,pwd.getpwnam引发一个KeyError

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

您可以使用类似于:

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

存储列表并检查username in list

相关问题 更多 >