如何通过登录找到用户 ID(*NIX 下的 Python)

发布于 2024-07-08 07:30:38 字数 171 浏览 8 评论 0原文

我需要将我的进程设置为在“无人”下运行,我找到了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吹泡泡o 2024-07-15 07:30:38

您可能想查看 python stdlib 中的 pwd 模块,例如:

import pwd
pw = pwd.getpwnam("nobody")
uid = pw.pw_uid

它使用 /etc/passwd (嗯,从技术上讲,它使用 posix C API,所以我想如果它不使用 /etc/passwd 但公开所需的功能,它可能在操作系统上工作),但比手动解析它更干净

You might want to have a look at the pwd module in the python stdlib, for example:

import pwd
pw = pwd.getpwnam("nobody")
uid = pw.pw_uid

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

土豪 2024-07-15 07:30:38

切勿直接扫描/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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文