如何通过登录找到用户 ID(*NIX 下的 Python)
我需要将我的进程设置为在“无人”下运行,我找到了 os.setuid(),但是如果我有 login
,如何找到 uid
?
我发现 uids 位于 /etc/passwd 中,但也许有比扫描 /etc/passwd 更Pythonic 的方法。 有人吗?
I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find uid
if I have login
?
I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想查看 python stdlib 中的 pwd 模块,例如:
它使用 /etc/passwd (嗯,从技术上讲,它使用 posix C API,所以我想如果它不使用 /etc/passwd 但公开所需的功能,它可能在操作系统上工作),但比手动解析它更干净
You might want to have a look at the pwd module in the python stdlib, for example:
it uses /etc/passwd (well, technically it uses the posix C API, so I suppose it might work on an OS if it didn't use /etc/passwd but exposed the needed functions) but is cleaner than parsing it manually
切勿直接扫描
/etc/passwd
。例如,在我管理的 Linux 系统上,用户帐户不在
/etc/passwd
上,而是在 LDAP 服务器上。正确的方法是使用
getpwent
/getgrent
和相关的 C 函数(如 @TFKyle 的答案),它将获取每个系统的正确方法的信息(在 Linux 上) glibc,它会读取/etc/nsswitch.conf
来了解要加载哪些 NSS 动态库来获取信息)。Never directly scan
/etc/passwd
.For instance, on a Linux system I administer, the user accounts are not on
/etc/passwd
, but on a LDAP server.The correct way is to use
getpwent
/getgrent
and related C functions (as in @TFKyle's answer), which will get the information on the correct way for each system (on Linux glibc, it reads/etc/nsswitch.conf
to know which NSS dynamic libraries to load to get the information).