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

耗尽温柔 提交于 2019-12-08 14:40:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!