如何使用 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
How to check if a user exists in a GNU/Linux OS using Python?
提问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-name
and 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...except
block.
这个答案建立在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
回答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