在 Python 和 linux 中如何获取给定的用户 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7770034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
in Python and linux how to get given user's id
提问by ren
There is os.getuid() which "Returns the currentprocess's user id.". But how do I find out any given user's id?
有 os.getuid() 它“返回当前进程的用户 ID。”。但是我如何找出任何给定用户的 ID?
采纳答案by NPE
回答by vines
You could just parse /etc/passwd
, it's stored there.
你可以 parse /etc/passwd
,它存储在那里。
回答by chown
pwd
:
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')
回答by murphstein
Assuming what you want is the username string associated with the userid for your program, try:
假设您想要的是与您的程序的用户 ID 关联的用户名字符串,请尝试:
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.
如果差异对您很重要,请使用 os.geteuid() 来获取有效的 uid。
Use pw_gecos instead of pw_name to get the "real name" if that's populated on your system.
如果在您的系统上填充了“真实姓名”,请使用 pw_gecos 而不是 pw_name 来获取“真实姓名”。