blob: 50f3bd005449dd82205e7fb22c36d515cd277d6b [file] [log] [blame]
Tor Norbye3a2425a52013-11-04 10:16:08 -08001"""
2Access to the Unix group database.
3
4Group entries are reported as 4-tuples containing the following fields
5from the group database, in order:
6
7 name - name of the group
8 passwd - group password (encrypted); often empty
9 gid - numeric ID of the group
10 mem - list of members
11
12The gid is an integer, name and password are strings. (Note that most
13users are not explicitly listed as members of the groups they are in
14according to the password database. Check both databases to get
15complete membership information.)
16"""
17
18__all__ = ['getgrgid', 'getgrnam', 'getgrall']
19
20from os import _name, _posix_impl
21from org.python.core.Py import newString
22
23if _name == 'nt':
24 raise ImportError, 'grp module not supported on Windows'
25
26class struct_group(tuple):
27 """
28 grp.struct_group: Results from getgr*() routines.
29
30 This object may be accessed either as a tuple of
31 (gr_name,gr_passwd,gr_gid,gr_mem)
32 or via the object attributes as named in the above tuple.
33 """
34
35 attrs = ['gr_name', 'gr_passwd', 'gr_gid', 'gr_mem']
36
37 def __new__(cls, grp):
38 grp = (newString(grp.name), newString(grp.password), int(grp.GID),
39 [newString(member) for member in grp.members])
40 return tuple.__new__(cls, grp)
41
42 def __getattr__(self, attr):
43 try:
44 return self[self.attrs.index(attr)]
45 except ValueError:
46 raise AttributeError
47
48
49def getgrgid(uid):
50 """
51 getgrgid(id) -> tuple
52 Return the group database entry for the given numeric group ID. If
53 id is not valid, raise KeyError.
54 """
55 entry = _posix_impl.getgrgid(uid)
56 if not entry:
57 raise KeyError(uid)
58 return struct_group(entry)
59
60
61def getgrnam(name):
62 """
63 getgrnam(name) -> tuple
64 Return the group database entry for the given group name. If
65 name is not valid, raise KeyError.
66 """
67 entry = _posix_impl.getgrnam(name)
68 if not entry:
69 raise KeyError(name)
70 return struct_group(entry)
71
72
73def getgrall():
74 """
75 getgrall() -> list of tuples
76 Return a list of all available group database entries,
77 in arbitrary order.
78 """
79 groups = []
80 while True:
81 group = _posix_impl.getgrent()
82 if not group:
83 break
84 groups.append(struct_group(group))
85 return groups