Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find userid by login (Python under *NIX)

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?

like image 918
Slava V Avatar asked Nov 16 '08 22:11

Slava V


2 Answers

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

like image 114
TFKyle Avatar answered Nov 17 '22 00:11

TFKyle


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

like image 32
CesarB Avatar answered Nov 17 '22 00:11

CesarB