Linux view all users of a user group (Python Implementation)

Time:2019-10-21

code

# encoding: utf-8
# author: walker
# date: 2017-07-31
#Summary: Linux view all users of a user group
# filename: group_users.py

import sys 

#Print all members of a group
def ShowGroupUsers(group_name):
    group_id = 'err'
    users = ''
    with open('/etc/group') as f:
        for line in f:
            line = line.strip()
            vec = line.split(':')
            if vec[0] == group_name:
                group_id = vec[2]
                users = vec[3]
    if group_id == 'err':
        print('not find %s in /etc/group')
        return False
        
    with open('/etc/passwd') as f:
         for line in f:
            line = line.strip()
            vec = line.split(':')
            if vec[3] == group_id:
                users += ',' + vec[0]
                
    user_set = set(filter(lambda x:x, users.split(',')))
    users = ','.join(sorted(list(user_set)))
    print('%s(%s) users: %s' % (group_name, group_id, users))

    return True


if __name__ == '__main__':
    ShowGroupUsers(sys.argv[1])

Use

python group_users.py groupX