code

# encoding: utf-8
# author: walker
# date: 2017-07-31
# summary: Linux 查看某个用户组的所有用户
# filename: group_users.py

import sys 

#打印某个组的所有成员
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])

使用

python group_users.py groupX

qbit
268 声望279 粉丝