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

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")

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.


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.') 

Tags:

Python

Unix