blob: f20169a1b3639fc8e4af19aa12d9984b6f0b5949 [file] [log] [blame]
Tor Norbye3a2425a2013-11-04 10:16:08 -08001"""
2This module provides access to the Unix password database.
3
4Password database entries are reported as 7-tuples containing the
5following items from the password database (see `<pwd.h>'), in order:
6pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell. The
7uid and gid items are integers, all others are strings. An exception
8is raised if the entry asked for cannot be found.
9"""
10
11__all__ = ['getpwuid', 'getpwnam', 'getpwall']
12
13from os import _name, _posix_impl
14from org.python.core.Py import newString
15
16if _name == 'nt':
17 raise ImportError, 'pwd module not supported on Windows'
18
19class struct_passwd(tuple):
20 """
21 pwd.struct_passwd: Results from getpw*() routines.
22
23 This object may be accessed either as a tuple of
24 (pw_name,pw_passwd,pw_uid,pw_gid,pw_gecos,pw_dir,pw_shell)
25 or via the object attributes as named in the above tuple.
26 """
27
28 attrs = ['pw_name', 'pw_passwd', 'pw_uid', 'pw_gid', 'pw_gecos',
29 'pw_dir', 'pw_shell']
30
31 def __new__(cls, pwd):
32 pwd = (newString(pwd.loginName), newString(pwd.password), int(pwd.UID),
33 int(pwd.GID), newString(pwd.GECOS), newString(pwd.home),
34 newString(pwd.shell))
35 return tuple.__new__(cls, pwd)
36
37 def __getattr__(self, attr):
38 try:
39 return self[self.attrs.index(attr)]
40 except ValueError:
41 raise AttributeError
42
43
44def getpwuid(uid):
45 """
46 getpwuid(uid) -> (pw_name,pw_passwd,pw_uid,
47 pw_gid,pw_gecos,pw_dir,pw_shell)
48 Return the password database entry for the given numeric user ID.
49 See pwd.__doc__ for more on password database entries.
50 """
51 entry = _posix_impl.getpwuid(uid)
52 if not entry:
53 raise KeyError(uid)
54 return struct_passwd(entry)
55
56
57def getpwnam(name):
58 """
59 getpwnam(name) -> (pw_name,pw_passwd,pw_uid,
60 pw_gid,pw_gecos,pw_dir,pw_shell)
61 Return the password database entry for the given user name.
62 See pwd.__doc__ for more on password database entries.
63 """
64 entry = _posix_impl.getpwnam(name)
65 if not entry:
66 raise KeyError(name)
67 return struct_passwd(entry)
68
69
70def getpwall():
71 """
72 getpwall() -> list_of_entries
73 Return a list of all available password database entries,
74 in arbitrary order.
75 See pwd.__doc__ for more on password database entries.
76 """
77 entries = []
78 while True:
79 entry = _posix_impl.getpwent()
80 if not entry:
81 break
82 entries.append(struct_passwd(entry))
83 return entries