in Python and linux how to get given user’s id [duplicate]

Each Answer to this Q is separated by one/two green lines.

There is os.getuid() which “Returns the current process’s user id.”. But how do I find out any given user’s id?

You could use pwd.getpwnam():

In [5]: pwd.getpwnam('aix').pw_uid
Out[5]: 1004

Assuming what you want is the username string associated with the userid for your program, try:

import os
import pwd
pwd.getpwuid( os.getuid() ).pw_name

Use os.geteuid() to get the effective uid instead, if that difference matters to you.

Use pw_gecos instead of pw_name to get the “real name” if that’s populated on your system.


import pwd
for p in pwd.getpwall():
    print p

pwd.struct_passwd(pw_name="_calendar", pw_passwd='*', pw_uid=93, pw_gid=93, pw_gecos="Calendar", pw_dir="/var/empty", pw_shell="/usr/bin/false")
pwd.struct_passwd(pw_name="_teamsserver", pw_passwd='*', pw_uid=94, pw_gid=94, pw_gecos="TeamsServer", pw_dir="/var/teamsserver", pw_shell="/usr/bin/false")
pwd.struct_passwd(pw_name="_update_sharing", pw_passwd='*', pw_uid=95, pw_gid=-2, pw_gecos="Update Sharing", pw_dir="/var/empty", pw_shell="/usr/bin/false")
pwd.struct_passwd(pw_name="_installer", pw_passwd='*', pw_uid=96, pw_gid=-2, pw_gecos="Installer", pw_dir="/var/empty", pw_shell="/usr/bin/false")
pwd.struct_passwd(pw_name="_atsserver", pw_passwd='*', pw_uid=97, pw_gid=97, pw_gecos="ATS Server", pw_dir="/var/empty", pw_shell="/usr/bin/false")
pwd.struct_passwd(pw_name="_ftp", pw_passwd='*', pw_uid=98, pw_gid=-2, pw_gecos="FTP Daemon", pw_dir="/var/empty", pw_shell="/usr/bin/false")

You could just parse /etc/passwd, it’s stored there.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .