Parand
Parand

Reputation: 106300

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

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

Answers (2)

bitmvr
bitmvr

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 and group_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 called grp.struct_group and getpwnam returns a class called pwd.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

dfa
dfa

Reputation: 116334

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]

Upvotes: 117

Related Questions