如何使用 Python 检查 GNU/Linux 操作系统中是否存在用户?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2540460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:53:21  来源:igfitidea点击:

How to check if a user exists in a GNU/Linux OS using Python?

pythonusername

提问by Elifarley

What is the easiest way to check the existence of a user on a GNU/Linux OS, using Python?

使用 Python 在 GNU/Linux 操作系统上检查用户是否存在的最简单方法是什么?

Anything better than issuing ls ~login-nameand checking the exit code?

有什么比发布ls ~login-name和检查退出代码更好的吗?

And if running under Windows?

如果在 Windows 下运行?

回答by Acumenus

This answer builds upon the answer by Brian. It adds the necessary try...exceptblock.

这个答案建立在Brian 的答案之上。它添加了必要的try...except块。

Check if a user exists:

检查用户是否存在:

import pwd

try:
    pwd.getpwnam('someusr')
except KeyError:
    print('User someusr does not exist.')

Check if a group exists:

检查组是否存在:

import grp

try:
    grp.getgrnam('somegrp')
except KeyError:
    print('Group somegrp does not exist.') 

回答by Brian Agnew

To look up my userid (bagnew) under Unix:

bagnew在 Unix 下查找我的用户 ID ( ):

import pwd
pw = pwd.getpwnam("bagnew")
uid = pw.pw_uid

See the pwdmodule info for more.

有关更多信息,请参阅pwd模块信息。

回答by Powertieke

Using pwd you can get a listing of all available user entries using pwd.getpwall(). This can work if you do not like try:/except: blocks.

使用 pwd,您可以使用 pwd.getpwall() 获取所有可用用户条目的列表。如果您不喜欢 try:/except: 块,这可以工作。

import pwd

username = "zomobiba"
usernames = [x[0] for x in pwd.getpwall()]
if username in usernames:
    print("Yay")

回答by Bill Sanders

I would parse /etc/passwd for the username in question. Users may not necessarily have homedir's.

我会为有问题的用户名解析 /etc/passwd 。用户可能不一定有 homedir。

回答by tshepang

Similar to this answer, I would do this:

此答案类似,我会这样做:

>>> import pwd
>>> 'tshepang' in [entry.pw_name for entry in pwd.getpwall()]
True