tags:

views:

85

answers:

3

In Python under Linux, what is the easiest way to check the existence of a user, given his/her login?

Anything better than issuing 'ls ~login-name' and checking the exit code?

And if running under Windows?

+7  A: 

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
It will raise `KeyError` if the username is not found.
Joe Koberg
@Joe - thanks for the clarification
Brian Agnew
Found some more info here: http://www.doughellmann.com/PyMOTW/pwd/
Elifarley
+1  A: 

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

Bill Sanders
This will fail if e.g. LDAP is being used.
Ignacio Vazquez-Abrams
+1 for mentioning that users may not necessarily have homedirs.
Andrei Ciobanu
I was under the impression that not all linux flavours store user info in the /etc/passwd file...
Powertieke
@Powertieke: They do, if the `passwd` or `shadow` NSS databases are using `files`. See the `nsswitch.conf(5)` man page for more details.
Ignacio Vazquez-Abrams
A: 

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

userid = "zomobiba"
if userid in [x[0] for x in pwd.getpwall()]:
    print "Yay"
Powertieke