SoFunction
Updated on 2025-03-01

Python to obtain a username group ID process analysis

getpwname can only get gid one username.

import pwd
myGroupId = (username).pw_gid

getgroups can only get groups script users.

import os
myGroupIds = ()

How can I get any username of all groups, such as id -Gn command?

id -Gn `whoami`

Solution

#!/usr/bin/env python
import grp, pwd 
user = "myname"
groups = [g.gr_name for g in () if user in g.gr_mem]
gid = (user).pw_gid
((gid).gr_name)
print groups

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.