Skip to content

Commit 6159754

Browse files
committed
groups: Add groups.py
1 parent beb9173 commit 6159754

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/groups.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/python3
2+
3+
import grp
4+
import pwd
5+
import os
6+
import sys
7+
from optparse import OptionParser
8+
9+
10+
def groups(_, usernames: list[str]):
11+
failed = False
12+
13+
for user in usernames or [os.getlogin()]:
14+
try:
15+
user_info = pwd.getpwnam(user)
16+
except KeyError as e:
17+
failed = True
18+
print(e, file=sys.stderr)
19+
continue
20+
21+
print(
22+
(user + " : " if usernames else "")
23+
+ " ".join(
24+
[
25+
grp.getgrgid(id).gr_name
26+
for id in os.getgrouplist(user, user_info.pw_gid)
27+
]
28+
),
29+
)
30+
31+
if failed:
32+
sys.exit(1)
33+
34+
35+
if __name__ == "__main__":
36+
parser = OptionParser(
37+
usage="Usage: %prog [USERNAME]...",
38+
description="Print a list of groups for each USERNAME or the current user.",
39+
add_help_option=False,
40+
)
41+
parser.add_option("--help", action="help", help="show usage information and exit")
42+
43+
groups(*parser.parse_args())

0 commit comments

Comments
 (0)