开发者

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

开发者 https://www.devze.com 2023-04-13 05:57 出处:网络
This question already has an answer here: Python: find开发者_如何学Pythoning uid/gid for a given username/groupname (for os.chown)
This question already has an answer here: Python: find开发者_如何学Pythoning uid/gid for a given username/groupname (for os.chown) (1 answer) Closed 7 years ago.

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.


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')


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号