-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgroups.py
More file actions
53 lines (44 loc) · 1.51 KB
/
groups.py
File metadata and controls
53 lines (44 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env python3
'''
Name: Hamdy Abou El Anein
Email: hamdy.aea@protonmail.com
Date of creation: 17-11-2024
Last update: 17-11-2024
Version: 1.0
Description: The groups command from GNU coreutils in Python3
Example of use: python3 groups.py username
'''
import sys
import argparse
import os
import grp
import pwd
def get_groups_for_user(username=None):
"""Return a list of groups a user belongs to."""
if username is None:
# If no username is provided, get the groups for the current user
username = os.getlogin()
# Get the user's ID
user_info = pwd.getpwnam(username)
# Get the list of groups for the user
groups = [g.gr_name for g in grp.getgrall() if username in g.gr_mem or g.gr_name == user_info.pw_name]
return groups
def main():
parser = argparse.ArgumentParser(
description="Print group memberships for each USERNAME or, if no USERNAME is specified, for the current process."
)
parser.add_argument(
"usernames", nargs="*", default=[os.getlogin()],
help="The usernames to query. If no USERNAME is provided, the current user is used."
)
parser.add_argument(
"--version", action="version", version="groups.py 1.0",
help="Show version and exit."
)
args = parser.parse_args()
# Process each username and print their groups
for username in args.usernames:
groups = get_groups_for_user(username)
print(f"{username}: {', '.join(groups)}")
if __name__ == "__main__":
main()