ยปCore Development>Code coverage>Lib/getpass.py

Python code coverage for Lib/getpass.py

#countcontent
1n/a"""Utilities to get a password and/or the current user name.
2n/a
3n/agetpass(prompt[, stream]) - Prompt for a password, with echo turned off.
4n/agetuser() - Get the user name from the environment or password database.
5n/a
6n/aGetPassWarning - This UserWarning is issued when getpass() cannot prevent
7n/a echoing of the password contents while reading.
8n/a
9n/aOn Windows, the msvcrt module will be used.
10n/aOn the Mac EasyDialogs.AskPassword is used, if available.
11n/a
12n/a"""
13n/a
14n/a# Authors: Piers Lauder (original)
15n/a# Guido van Rossum (Windows support and cleanup)
16n/a# Gregory P. Smith (tty support & GetPassWarning)
17n/a
18n/aimport contextlib
19n/aimport io
20n/aimport os
21n/aimport sys
22n/aimport warnings
23n/a
24n/a__all__ = ["getpass","getuser","GetPassWarning"]
25n/a
26n/a
27n/aclass GetPassWarning(UserWarning): pass
28n/a
29n/a
30n/adef unix_getpass(prompt='Password: ', stream=None):
31n/a """Prompt for a password, with echo turned off.
32n/a
33n/a Args:
34n/a prompt: Written on stream to ask for the input. Default: 'Password: '
35n/a stream: A writable file object to display the prompt. Defaults to
36n/a the tty. If no tty is available defaults to sys.stderr.
37n/a Returns:
38n/a The seKr3t input.
39n/a Raises:
40n/a EOFError: If our input tty or stdin was closed.
41n/a GetPassWarning: When we were unable to turn echo off on the input.
42n/a
43n/a Always restores terminal settings before returning.
44n/a """
45n/a passwd = None
46n/a with contextlib.ExitStack() as stack:
47n/a try:
48n/a # Always try reading and writing directly on the tty first.
49n/a fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
50n/a tty = io.FileIO(fd, 'w+')
51n/a stack.enter_context(tty)
52n/a input = io.TextIOWrapper(tty)
53n/a stack.enter_context(input)
54n/a if not stream:
55n/a stream = input
56n/a except OSError as e:
57n/a # If that fails, see if stdin can be controlled.
58n/a stack.close()
59n/a try:
60n/a fd = sys.stdin.fileno()
61n/a except (AttributeError, ValueError):
62n/a fd = None
63n/a passwd = fallback_getpass(prompt, stream)
64n/a input = sys.stdin
65n/a if not stream:
66n/a stream = sys.stderr
67n/a
68n/a if fd is not None:
69n/a try:
70n/a old = termios.tcgetattr(fd) # a copy to save
71n/a new = old[:]
72n/a new[3] &= ~termios.ECHO # 3 == 'lflags'
73n/a tcsetattr_flags = termios.TCSAFLUSH
74n/a if hasattr(termios, 'TCSASOFT'):
75n/a tcsetattr_flags |= termios.TCSASOFT
76n/a try:
77n/a termios.tcsetattr(fd, tcsetattr_flags, new)
78n/a passwd = _raw_input(prompt, stream, input=input)
79n/a finally:
80n/a termios.tcsetattr(fd, tcsetattr_flags, old)
81n/a stream.flush() # issue7208
82n/a except termios.error:
83n/a if passwd is not None:
84n/a # _raw_input succeeded. The final tcsetattr failed. Reraise
85n/a # instead of leaving the terminal in an unknown state.
86n/a raise
87n/a # We can't control the tty or stdin. Give up and use normal IO.
88n/a # fallback_getpass() raises an appropriate warning.
89n/a if stream is not input:
90n/a # clean up unused file objects before blocking
91n/a stack.close()
92n/a passwd = fallback_getpass(prompt, stream)
93n/a
94n/a stream.write('\n')
95n/a return passwd
96n/a
97n/a
98n/adef win_getpass(prompt='Password: ', stream=None):
99n/a """Prompt for password with echo off, using Windows getch()."""
100n/a if sys.stdin is not sys.__stdin__:
101n/a return fallback_getpass(prompt, stream)
102n/a
103n/a for c in prompt:
104n/a msvcrt.putwch(c)
105n/a pw = ""
106n/a while 1:
107n/a c = msvcrt.getwch()
108n/a if c == '\r' or c == '\n':
109n/a break
110n/a if c == '\003':
111n/a raise KeyboardInterrupt
112n/a if c == '\b':
113n/a pw = pw[:-1]
114n/a else:
115n/a pw = pw + c
116n/a msvcrt.putwch('\r')
117n/a msvcrt.putwch('\n')
118n/a return pw
119n/a
120n/a
121n/adef fallback_getpass(prompt='Password: ', stream=None):
122n/a warnings.warn("Can not control echo on the terminal.", GetPassWarning,
123n/a stacklevel=2)
124n/a if not stream:
125n/a stream = sys.stderr
126n/a print("Warning: Password input may be echoed.", file=stream)
127n/a return _raw_input(prompt, stream)
128n/a
129n/a
130n/adef _raw_input(prompt="", stream=None, input=None):
131n/a # This doesn't save the string in the GNU readline history.
132n/a if not stream:
133n/a stream = sys.stderr
134n/a if not input:
135n/a input = sys.stdin
136n/a prompt = str(prompt)
137n/a if prompt:
138n/a try:
139n/a stream.write(prompt)
140n/a except UnicodeEncodeError:
141n/a # Use replace error handler to get as much as possible printed.
142n/a prompt = prompt.encode(stream.encoding, 'replace')
143n/a prompt = prompt.decode(stream.encoding)
144n/a stream.write(prompt)
145n/a stream.flush()
146n/a # NOTE: The Python C API calls flockfile() (and unlock) during readline.
147n/a line = input.readline()
148n/a if not line:
149n/a raise EOFError
150n/a if line[-1] == '\n':
151n/a line = line[:-1]
152n/a return line
153n/a
154n/a
155n/adef getuser():
156n/a """Get the username from the environment or password database.
157n/a
158n/a First try various environment variables, then the password
159n/a database. This works on Windows as long as USERNAME is set.
160n/a
161n/a """
162n/a
163n/a for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
164n/a user = os.environ.get(name)
165n/a if user:
166n/a return user
167n/a
168n/a # If this fails, the exception will "explain" why
169n/a import pwd
170n/a return pwd.getpwuid(os.getuid())[0]
171n/a
172n/a# Bind the name getpass to the appropriate function
173n/atry:
174n/a import termios
175n/a # it's possible there is an incompatible termios from the
176n/a # McMillan Installer, make sure we have a UNIX-compatible termios
177n/a termios.tcgetattr, termios.tcsetattr
178n/aexcept (ImportError, AttributeError):
179n/a try:
180n/a import msvcrt
181n/a except ImportError:
182n/a getpass = fallback_getpass
183n/a else:
184n/a getpass = win_getpass
185n/aelse:
186n/a getpass = unix_getpass