How to check if a user exists in a GNU/Linux OS using Python?
What is the easiest way to check the existence of a user on a GNU/Linux OS, using Python?
Anything better than issuing开发者_开发知识库 ls ~login-name
and checking the exit code?
And if running under Windows?
This answer builds upon the answer by Brian. It adds the necessary try...except
block.
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.')
To look up my userid (bagnew
) under Unix:
import pwd
pw = pwd.getpwnam("bagnew")
uid = pw.pw_uid
See the pwd module info for more.
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.
import pwd
username = "zomobiba"
usernames = [x[0] for x in pwd.getpwall()]
if username in usernames:
print("Yay")
I would parse /etc/passwd for the username in question. Users may not necessarily have homedir's.
Similar to this answer, I would do this:
>>> import pwd
>>> 'tshepang' in [entry.pw_name for entry in pwd.getpwall()]
True
精彩评论