Reputation: 106300
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
Upvotes: 77
Views: 56351
Reputation: 129
Attempting to help clarify previous examples.
Use the pwd
and grp
modules.
from pwd import getpwnam
from grp import getgrnam
Within your code where the need is to extract the UIDs for name
and group
, you will use the following.
Note: The parameters
user_name
andgroup_name
are placeholders. Replace them with the actual names you're targeting.
getpwnam('user_name').pw_uid # Returns UID only
getgrnam('group_name').gr_gid # Returns GID only
Note:
getgrnam
returns a class calledgrp.struct_group
andgetpwnam
returns a class calledpwd.struct_passwd
. As previously mentioned, you can access the ids from that struct via an index (i.e.getpwnam('user_name')[2]
) or through dot notation as shown in the example(s) above.
Upvotes: 3