in Python and linux how to get given user's id

Question:

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

Asked By: ren

||

Answers:

You could use pwd.getpwnam():

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

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

Answered By: vines

pwd:

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')
Answered By: chown

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.

Answered By: murphstein
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.