There is os.getuid() which "Returns the current process’s user id.". But how do I find out any given user's id?
Asked
Active
Viewed 5.4k times
4 Answers
41
You could use pwd.getpwnam()
:
In [5]: pwd.getpwnam('aix').pw_uid
Out[5]: 1004

NPE
- 486,780
- 108
- 951
- 1,012
37
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.

murphstein
- 509
- 3
- 4
7
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')

chown
- 51,908
- 16
- 134
- 170
-5
You could just parse /etc/passwd
, it's stored there.

vines
- 5,160
- 1
- 27
- 49
-
10It might be stored there, or in NIS, or in LDAP, or in any other source for which there's an nsswitch module. That's why we have APIs that start with `getpw` — so that you don't have a bug because you parsed `/etc/passwd` by hand on a system that uses (say) NIS to store user information. – mkj Oct 14 '11 at 15:55
-
mkj: Thanks! Didn't know about NIS and LDAP. – vines Oct 14 '11 at 16:01