Tor Norbye | 3a2425a5 | 2013-11-04 10:16:08 -0800 | [diff] [blame] | 1 | """ |
| 2 | Access to the Unix group database. |
| 3 | |
| 4 | Group entries are reported as 4-tuples containing the following fields |
| 5 | from 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 | |
| 12 | The gid is an integer, name and password are strings. (Note that most |
| 13 | users are not explicitly listed as members of the groups they are in |
| 14 | according to the password database. Check both databases to get |
| 15 | complete membership information.) |
| 16 | """ |
| 17 | |
| 18 | __all__ = ['getgrgid', 'getgrnam', 'getgrall'] |
| 19 | |
| 20 | from os import _name, _posix_impl |
| 21 | from org.python.core.Py import newString |
| 22 | |
| 23 | if _name == 'nt': |
| 24 | raise ImportError, 'grp module not supported on Windows' |
| 25 | |
| 26 | class 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 | |
| 49 | def 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 | |
| 61 | def 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 | |
| 73 | def 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 |