Search code examples
pythonlinuxunixprocess-management

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?


Solution

  • 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