Python: How to get group ids of one username (like id -Gn )
The following works assuming you are only interested in local users only, it will not work for things such as sssd
backed by a catalog server (for instance, ldap
).
#!/usr/bin/env python
import grp, pwd
user = "myname"
groups = [g.gr_name for g in grp.getgrall() if user in g.gr_mem]
gid = pwd.getpwnam(user).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
print groups
If you want the current user's groups.
import os, grp
[grp.getgrgid(g).gr_name for g in os.getgroups()]
os.getgroups()
returns the list of gids of the current user.
grp.getgrgid(g)
returns details about a group