24

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?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Elifarley
  • 1,310
  • 3
  • 16
  • 23

5 Answers5

42

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.') 
Community
  • 1
  • 1
Asclepius
  • 57,944
  • 17
  • 167
  • 143
10

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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
5

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")
Asclepius
  • 57,944
  • 17
  • 167
  • 143
Powertieke
  • 2,368
  • 1
  • 14
  • 21
  • 4
    Okay, but there is no reason not to like `try...except` blocks. It is also more efficient to query a single user with `getpwnam` than to query all users with `getpwall`. – Asclepius Mar 01 '13 at 23:26
0

I would parse /etc/passwd for the username in question. Users may not necessarily have homedir's.

-1

Similar to this answer, I would do this:

>>> import pwd
>>> 'tshepang' in [entry.pw_name for entry in pwd.getpwall()]
True
Community
  • 1
  • 1
tshepang
  • 12,111
  • 21
  • 91
  • 136