问题
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?
回答1:
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.')
回答2:
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.
回答3:
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")
回答4:
I would parse /etc/passwd for the username in question. Users may not necessarily have homedir's.
回答5:
Similar to this answer, I would do this:
>>> import pwd
>>> 'tshepang' in [entry.pw_name for entry in pwd.getpwall()]
True
来源:https://stackoverflow.com/questions/2540460/how-to-check-if-a-user-exists-in-a-gnu-linux-os-using-python