Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: finding uid/gid for a given username/groupname (for os.chown)

Tags:

python

What's a good way to find the uid/gid for a given username or groupname using Python? I need to set file ownership with os.chown and need the integer ids instead of the alphabetic.

[Quick note]: getpwnam works great but is not available on windows, so here's some code that creates stubs to allow you to run the same code on windows and unix.

try:     from pwd import getpwnam except:     getpwnam = lambda x: (0,0,0)     os.chown = lambda x, y, z: True     os.chmod = lambda x, y: True     os.fchown = os.chown     os.fchmod = os.chmod 
like image 554
Parand Avatar asked May 05 '09 17:05

Parand


People also ask

What command gives you the UID and GIDs associated with an account?

In Linux, how do I find a user's UID or GID? To find a user's UID (user ID) or GID (group ID) and other information in Linux/Unix-like operating systems, use the id command.

What is the default UID & GID of root user?

The root account has the awesome privilege of having UID = 0 and GID = 0. These numbers are what give the root account its overwhelming power.


1 Answers

Use the pwd and grp modules:

from pwd import getpwnam    print getpwnam('someuser')[2] # or print getpwnam('someuser').pw_uid print grp.getgrnam('somegroup')[2] 
like image 80
dfa Avatar answered Oct 06 '22 00:10

dfa